一致性hash.md

2016-08-03  本文已影响92人  jey恒

jedis中sharejedis一致性hash实现

http://blog.csdn.net/yfkiss/article/details/7337382
https://sites.google.com/site/murmurhash/


public static final int DEFAULT_WEIGHT = 1;

private TreeMap<Long, S> nodes; 
private final Hashing algo;// hash算法
//shardinfo对应的jedis连接
private final Map<ShardInfo<R>, R> resources = new LinkedHashMap<ShardInfo<R>, R>();


//shards 所有的服务器节点列表

private void initialize(List<S> shards) {

  // TreeMap的hash环
  nodes = new TreeMap<Long, S>();
  
  // 遍历节点
  for (int i = 0; i != shards.size(); ++i) {
    final S shardInfo = shards.get(i);
     //每个节点创建160个虚拟节点
    if (shardInfo.getName() == null) 
      for (int n = 0; n < 160 * shardInfo.getWeight(); n++){
      nodes.put(this.algo.hash("SHARD-" + i + "-NODE-" + n), shardInfo);
      }
    else for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {
      nodes.put(this.algo.hash(shardInfo.getName() + "*" + shardInfo.getWeight() + n), shardInfo);
    }
    resources.put(shardInfo, shardInfo.createResource());
  }
}

// 获取一个节点
public S getShardInfo(byte[] key) {
  //返回大于key的部分子map
  SortedMap<Long, S> tail = nodes.tailMap(algo.hash(key));
  if (tail.isEmpty()) {
    return nodes.get(nodes.firstKey());
  }
  
  //返回map中key值最小的一个
  return tail.get(tail.firstKey());
}

// 获得一个jedis
public R getShard(String key) {
  return resources.get(getShardInfo(key));
}

public S getShardInfo(String key) {
  return getShardInfo(SafeEncoder.encode(getKeyTag(key)));
}

上一篇 下一篇

猜你喜欢

热点阅读