之前一直没仔细看过ShardedJedis的代码,最近遇到了shard后集群扩容后的数据迁移问题。
今天在看ShardedJedis源码的时候,发现ShardedJedis并没有使用节点的Ip和port做hash,而是用的instance的顺序或者name,太赞了。
private void initialize(List shards) {
nodes = new TreeMap
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());
}
}
配置的时候也非常简单:
一开始你可以设置足够多的instance,数据扩容的时候,只需要将几个instance的数据copy到别的机器上。
然后修改配置文件的ip和端口即可。很方便吧?
另外,Jedis还提供了对jedis sentinel pool的封装,所以发生主从切换的时候,web server都不需要重新配置和deploy。高可用性的极佳体现啊。
@Autowired private JedisSentinelPool pool;
public void mymethod() {
Jedis jedis = null;
try {
jedis = pool.getResource();
jedis.hset(....
} catch (JedisException je) {
throw je;
} finally {
if (jedis != null) pool.returnResource(jedis);
}
}
spring bean的配置: