ShardedJedis部分源碼 redis分佈式直連同步方式

ShardedJedis redis分佈式直連同步

==============================================================


Sharded類中4個屬性,2個重要方法:

4個屬性 

public static final int DEFAULT_WEIGHT = 1;//權重
private final Hashing algo;//哈希
private TreeMap<Long, S> nodes;//虛擬節點
private final Map<ShardInfo<R>, R> resources = new LinkedHashMap<ShardInfo<R>, R>();//真實節點
兩個重要方法
1.new JedisShardInfo()時調用,算是初始化
private void initialize(List<S> shards) {
    nodes = new TreeMap<Long, S>();

    for (int i = 0; i != shards.size(); ++i) {
      final S shardInfo = shards.get(i);
      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());//shardInfo.createResource() = new Jedis()
    }
  }
160爲虛擬節點基數,shardInfo.getWeight()權重越大,虛擬節點數越多,越容易存取到該節點
nodes和resources結合使用,找到虛擬節點對應的真實節點

2.get()/set()方法時調用,獲取存取數據到的具體Jedis
public R getShard(String key) {
    return resources.get(getShardInfo(key));
  }

  public S getShardInfo(byte[] key) {
    SortedMap<Long, S> tail = nodes.tailMap(algo.hash(key));
    if (tail.isEmpty()) {
      return nodes.get(nodes.firstKey());
    }
    return tail.get(tail.firstKey());
  }
TreeMap、nodes.tailMap()、SortedMap
實現一致性哈希旋轉概念(找到最近的節點)


ShardedJedis.java
-----------------------------------------------------
public String set(String key, String value) {
    Jedis j = getShard(key);
    return j.set(key, value);
  }

public String get(String key) {
    Jedis j = getShard(key);
    return j.get(key);
  }
......
-----------------------------------------------------

BinaryShardedJedis.java
-----------------------------------------------------
public String set(byte[] key, byte[] value) {
    Jedis j = getShard(key);
    return j.set(key, value);
  }

public byte[] get(byte[] key) {
    Jedis j = getShard(key);
    return j.get(key);
  }
......
-----------------------------------------------------


TreeMap、treeMap.tailMap()、SortedMap示例:

public static void main(String[] args) {
		// creating maps
		TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();

		// populating tree map
		treemap.put(2, "two");
		treemap.put(1, "one");
		treemap.put(3, "three");
		treemap.put(6, "six");
		treemap.put(5, "five");

		SortedMap<Integer, String> treemapincl = treemap.tailMap(3);//該方法調用返回此映射,其鍵大於或等於fromKey(這裏是3)的值
		System.out.println("Tail map values: " + treemapincl);
		// 執行結果: Tail map values: {3=three, 5=five, 6=six}
	}

發佈了80 篇原創文章 · 獲贊 40 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章