您的位置:首页 > 数据库 > Redis

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

2016-11-15 14:21 211 查看
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}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息