[Java] Consistent Hashing →→→→→进入此内容的聊天室

来自 , 2021-01-08, 写在 Java, 查看 113 次.
URL http://www.code666.cn/view/0a0a0c8a
  1. import java.util.Collection;
  2. import java.util.SortedMap;
  3. import java.util.TreeMap;
  4.  
  5. public class ConsistentHash<T> {
  6.  
  7.  private final HashFunction hashFunction;
  8.  private final int numberOfReplicas;
  9.  private final SortedMap<Integer, T> circle = new TreeMap<Integer, T>();
  10.  
  11.  public ConsistentHash(HashFunction hashFunction, int numberOfReplicas,
  12.      Collection<T> nodes) {
  13.    this.hashFunction = hashFunction;
  14.    this.numberOfReplicas = numberOfReplicas;
  15.  
  16.    for (T node : nodes) {
  17.      add(node);
  18.    }
  19.  }
  20.  
  21.  public void add(T node) {
  22.    for (int i = 0; i < numberOfReplicas; i++) {
  23.      circle.put(hashFunction.hash(node.toString() + i), node);
  24.    }
  25.  }
  26.  
  27.  public void remove(T node) {
  28.    for (int i = 0; i < numberOfReplicas; i++) {
  29.      circle.remove(hashFunction.hash(node.toString() + i));
  30.    }
  31.  }
  32.  
  33.  public T get(Object key) {
  34.    if (circle.isEmpty()) {
  35.      return null;
  36.    }
  37.    int hash = hashFunction.hash(key);
  38.    if (!circle.containsKey(hash)) {
  39.      SortedMap<Integer, T> tailMap = circle.tailMap(hash);
  40.      hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
  41.    }
  42.    return circle.get(hash);
  43.  }
  44.  
  45. }//源代码片段来自云代码http://yuncode.net
  46.                        

回复 "Consistent Hashing"

这儿你可以回复上面这条便签

captcha