ShardedJedis部分源码 redis分布式直连同步方式

来源:互联网 发布:水暖毯和电热毯 知乎 编辑:程序博客网 时间:2024/04/20 20:53

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 mapsTreeMap<Integer, String> treemap = new TreeMap<Integer, String>();// populating tree maptreemap.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}}

0 0
原创粉丝点击