一致性hash.md

jedis中sharejedis一致性hash實現(xiàn)

  • Redis服務(wù)器節(jié)點劃分:將每臺服務(wù)器節(jié)點采用hash算法劃分為160個虛擬節(jié)點(可以配置劃分權(quán)重)
  • 將劃分虛擬節(jié)點采用TreeMap存儲
  • 對每個Redis服務(wù)器的物理連接采用LinkedHashMap存儲
  • 對Key or KeyTag 采用同樣的hash算法,然后從TreeMap獲取大于等于鍵hash值得節(jié)點,取最鄰近節(jié)點存儲;當(dāng)* * key的hash值大于虛擬節(jié)點hash值得最大值時,存入第一個虛擬節(jié)點
  • sharded采用的hash算法:MD5 和 MurmurHash兩種;默認(rèn)采用64位的MurmurHash算法;有興趣的可以 研究下,MurmurHash是一種高效,低碰撞的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對應(yīng)的jedis連接
private final Map<ShardInfo<R>, R> resources = new LinkedHashMap<ShardInfo<R>, R>();


//shards 所有的服務(wù)器節(jié)點列表

private void initialize(List<S> shards) {

  // TreeMap的hash環(huán)
  nodes = new TreeMap<Long, S>();
  
  // 遍歷節(jié)點
  for (int i = 0; i != shards.size(); ++i) {
    final S shardInfo = shards.get(i);
     //每個節(jié)點創(chuàng)建160個虛擬節(jié)點
    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());
  }
}

// 獲取一個節(jié)點
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)));
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 從三月份找實習(xí)到現(xiàn)在,面了一些公司,掛了不少,但最終還是拿到小米、百度、阿里、京東、新浪、CVTE、樂視家的研發(fā)崗...
    時芥藍(lán)閱讀 42,810評論 11 349
  • 第一章 Nginx簡介 Nginx是什么 沒有聽過Nginx?那么一定聽過它的“同行”Apache吧!Ngi...
    JokerW閱讀 33,022評論 24 1,002
  • 通過近期閱讀李笑來老師的文章。額、怎么說呢?貌似收獲并不是那么大!但是、還是有一點收獲的、那算不算是收獲呢!例如、...
    愛吃糖的艾糖閱讀 183評論 0 0
  • 突然想起之前在方所聽了Tango的講座。 忘了最早知道他是從哪看的,印象中是個廣告人,擅長腦洞漫畫,原名高幼軍,有...
    兔子鈺閱讀 1,855評論 2 13
  • 常??簇埵宓纳钜故畡t,深有感悟,每天的總結(jié)感悟都在內(nèi)了,我也試試: 1.最近發(fā)現(xiàn)我是個情緒化嚴(yán)重的人,任何事都能影...
    凌云仙渡閱讀 285評論 5 4

友情鏈接更多精彩內(nèi)容