最近做新旧系统做会话统一,新旧系统都是用redis存储会话,原以为很简单的事情,然而出现了奇怪现象。新系统创建了会话,理论上旧系统就可以正常访问,但是出现时而可以,时而不行(报会话不存在需登录)。
本地debug,用新系统创建的token在旧系统上查,确实有的可以查到,有的不行。由于系统是用Jedis分片模式(ShardedJedis),猜测新系统把会话存在A节点,旧系统去B节点查,但是同一个token hash后应该是同一个节点才是,查了下两个系统用的Jedis版本不一样,感觉问题接近了,一查代码果然
新系统
redis.clients.util.Sharded#initialize
private void initialize(List<S> shards) {
this.nodes = new TreeMap();
for(int i = 0; i != shards.size(); ++i) {
S shardInfo = (ShardInfo)shards.get(i);
int n;
if (shardInfo.getName() == null) {
for(n = 0; n < 160 * shardInfo.getWeight(); ++n) {
this.nodes.put(this.algo.hash("SHARD-" + i + "-NODE-" + n), shardInfo);
}
} else {
for(n = 0; n < 160 * shardInfo.getWeight(); ++n) {
//就是这行代码不同,导致一致性hash的环不同
this.nodes.put(this.algo.hash(shardInfo.getName() + "*" + n), shardInfo);
}
}
this.resources.put(shardInfo, shardInfo.createResource());
}
}
旧系统
redis.clients.util.Sharded#initialize
private void initialize(List<S> shards) {
this.nodes = new TreeMap();
for(int i = 0; i != shards.size(); ++i) {
S shardInfo = (ShardInfo)shards.get(i);
int n;
if (shardInfo.getName() == null) {
for(n = 0; n < 160 * shardInfo.getWeight(); ++n) {
this.nodes.put(this.algo.hash("SHARD-" + i + "-NODE-" + n), shardInfo);
}
} else {
for(n = 0; n < 160 * shardInfo.getWeight(); ++n) {
//就是这行代码不同,导致一致性hash的环不同
this.nodes.put(this.algo.hash(shardInfo.getName() + "*" + shardInfo.getWeight() + n), shardInfo);
}
}
this.resources.put(shardInfo, shardInfo.createResource());
}
}
原来Jedis2.10.0前的版本和之后的版本,一致性hash环实现不一样了,导致同样的key定位的节点不同,出现了开头的问题,所以版本统一是多么重要啊。
这里顺提一嘴,原来redis的一致性hash是使用TreeMap实现的~ 想要知道某个key落到哪个节点,使用TreeMap.tailMap就可以了,真是方便!