jedis分片原理剖析

Redis2.0+版本不支持服务器分片,只能通过jedis分片,3.0+以上支持hash槽的服务端分片。jedis的详细分片实现如下,其中murmurhash是当前主流的分片算法。

/**

* 机器分片的方式

* 注意jedis服务器影响分片的两个因素

* 1、权重

* 2、添加的顺序

* @param args

*/

public static void main(String[] args){

TreeMap nodes = new TreeMap();

ShardJedisTest murmurHash = new ShardJedisTest();

List shards = new ArrayList();

JedisShardInfo jedisShardInfo1 = new JedisShardInfo("172.20.158.140", 5415,3000, 20);

jedisShardInfo1.setPassword("test1234");

shards.add(jedisShardInfo1);

JedisShardInfo jedisShardInfo2 = new JedisShardInfo("172.20.158.140", 5414,3000, 20);

jedisShardInfo2.setPassword("test1234");

shards.add(jedisShardInfo2);

for (int i = 0; i != shards.size();++i) {

final JedisShardInfo shardInfo = shards.get(i);

if (shardInfo.getName() == null)

for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {

nodes.put(murmurHash.hash("SHARD-" + i + "-NODE-" + n), shardInfo);

}

else

for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {

nodes.put(murmurHash.hash(shardInfo.getName()+ "*" + shardInfo.getWeight() + n), shardInfo);

}

}

String key ="USER_KEY_3010040405052";

long murmurhashCode = murmurHash.hash(key);

JedisShardInfo jedisShardInfo =null;

SortedMap tail = nodes.tailMap(murmurhashCode);

if (tail.size() == 0) {

jedisShardInfo = (JedisShardInfo) nodes.get(nodes.firstKey());

}

jedisShardInfo= tail.get(tail.firstKey());

System.out.println("key:"+key+" murmurhashCode:"+murmurhashCode+" jedisShardInfo:"+jedisShardInfo);

}

你可能感兴趣的:(jedis分片原理剖析)