当前位置 : 主页 > 编程语言 > java >

Consistent Hash Java implementation

来源:互联网 收集:自由互联 发布时间:2021-06-28
consist_hash.java import java.nio.charset.Charset;import java.util.Collection;import java.util.SortedMap;import java.util.TreeMap;import com.google.common.hash.HashCode;import com.google.common.hash.HashFunction;public class ConsistentHash
consist_hash.java
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.SortedMap;
import java.util.TreeMap;

import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;

public class ConsistentHash
 
   {

	private final HashFunction hashFunction;
	private final int numberOfReplicas;
	private final SortedMap
  
    circle = new TreeMap
   
    (); public ConsistentHash(HashFunction hashFunction, int numberOfReplicas, Collection
    
      nodes) { this.hashFunction = hashFunction; this.numberOfReplicas = numberOfReplicas; for (T node : nodes) { add(node); } } public void add(T node) { for (int i = 0; i < numberOfReplicas; i++) { circle.put(hashFunction.hashString(node.toString() + i, Charset.defaultCharset()).asInt(), node); } } public void remove(T node) { for (int i = 0; i < numberOfReplicas; i++) { circle.remove(hashFunction.hashString(node.toString() + i, Charset.defaultCharset()).asInt()); } } public T get(Object key) { if (circle.isEmpty()) { return null; } HashCode hashCode = hashFunction.hashString((String) key, Charset.defaultCharset()); int hash = hashCode.asInt(); if (!circle.containsKey(hash)) { SortedMap
     
       tailMap = circle.tailMap(hash); hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey(); } return circle.get(hash); } }
     
    
   
  
 
网友评论