welcome to xlongwei.com

欢迎大家一起学习、交流、分享


QQ群:162333776 邮箱:admin@xlongwei.com

jedis sharded 对象池


分类 Java   关键字 分享   标签 java   linux   spring   redis   发布 hongwei  1472117306740
注意 转载须保留原文链接,译文链接,作者译者等信息。  
redis 分片模式,直接使用ShardedJedis会抛异常,java.lang.Long cannot be cast to [B,可能是因为连接不稳定,因此使用对象池模式:ShardedJedisPool。

单点故障时,重新获取可用节点,重建对象池
private void reshard() {
List<JedisShardInfo> list = reshard(nodes);
if(list!=null) {
shardedJedisPool = new ShardedJedisPool(poolConfig, list);
logger.warn("shardedJedis resharded");
}
}

缓存操作时,从对象池中获取ShardedJedis,用完后归还
public ValueWrapper get(Object key) {
ShardedJedis shardedJedis = null;
try {
shardedJedis = myShardedRedisCacheManager.shardedJedisPool.getResource();
byte[] computeKey = computeKey(key);
byte[] bs = shardedJedis.get(computeKey);
Object value = valueSerializer.deserialize(bs);
return (bs == null ? null : new SimpleValueWrapper(value));
}catch(JedisException e) {
myShardedRedisCacheManager.reshard();
}catch(Exception e) {
logger.warn(e.getMessage());
}finally {
if(shardedJedis != null) myShardedRedisCacheManager.shardedJedisPool.returnResource(shardedJedis);
}
return null;
}

直接使用ShardedJedis,在put和get都容易抛异常,而且难以恢复正常;改用对象池后就正常多了。