Skip to content

Instantly share code, notes, and snippets.

@YorkHwang
Last active October 20, 2019 14:50
Show Gist options
  • Save YorkHwang/ded9e32ec461e6fec72cdfdc0c05327c to your computer and use it in GitHub Desktop.
Save YorkHwang/ded9e32ec461e6fec72cdfdc0c05327c to your computer and use it in GitHub Desktop.
JedisPool loss data
I use JedisPool to connect redis,but it loss data.
codes are:
public void afterPropertiesSet() throws Exception {
Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();
//Jedis Cluster will attempt to discover cluster nodes automatically
String[] servers = server.split(";|,");
for (String str : servers) {
String[] ap = str.split(":");
HostAndPort hp = new HostAndPort(ap[0], Integer.valueOf(ap[1]));
jedisClusterNodes.add(hp);
}
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
config.setMaxTotal(maxTotal); //可用连接实例的最大数目,默认值为8;如果赋值为-1,则表示不限制;
config.setMaxIdle(100); //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值是8。
config.setMinIdle(10); //控制一个pool最少有多少个状态为idle(空闲的)的jedis实例,默认值是0。
config.setMaxWaitMillis(maxWait);//等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出
config.setTestOnBorrow(true);
config.setTestOnReturn(true);
jedisCluster = new JedisCluster(jedisClusterNodes,1000,2,config);
initJedisPool();
}
private void initJedisPool(){
if(!w.tryLock()){
logger.info("initJedisPool trylock fail.");
return;
}
try {
Field connHandler = ReflectionUtils.findField(BinaryJedisCluster.class, "connectionHandler");
connHandler.setAccessible(true);
JedisClusterConnectionHandler jc = (JedisClusterConnectionHandler) ReflectionUtils.getField(connHandler,jedisCluster);
Field infoCache = ReflectionUtils.findField(JedisClusterConnectionHandler.class, "cache");
infoCache.setAccessible(true);
clusterInfoCache = (JedisClusterInfoCache) ReflectionUtils.getField(infoCache,jc);
Field soltMap = ReflectionUtils.findField(JedisClusterInfoCache.class, "slots");
soltMap.setAccessible(true);
slots = (Map<Integer, JedisPool>)ReflectionUtils.getField(soltMap,clusterInfoCache);
//每个redis实例只有一个连接池
nodes = clusterInfoCache.getNodes() ;
if(nodes != null){
for(String nodeKey : nodes.keySet()){
nodeKeys.put(nodes.get(nodeKey), nodeKey) ;
}
}
renewSlotCache.invalidate(_key);
logger.warn("initJedisPool success.");
} catch (Exception e) {
logger.error("initJedisPool error " , e);
}finally{
w.unlock();
}
}
We can referece those :
https://gist.github.com/JonCole/b6354d92a2d51c141490f10142884ea4
https://stackoverflow.com/questions/26780531/data-loss-in-redis-through-jedis
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment