list操作 rediscluster_Redis集群批量操作
/*** 根據(jù)key計(jì)算slot,
* 再根據(jù)slot計(jì)算node,
* 獲取pipeline
* 進(jìn)行批量操作*/
public classBatchUtil {public static Mapmget(JedisCluster jc, String... keys){
Map resMap = new HashMap<>();if(keys == null || keys.length == 0){returnresMap;
}//如果只有一條,直接使用get即可
if(keys.length == 1){
resMap.put(keys[0], jc.get(keys[0]));returnresMap;
}//JedisCluster繼承了BinaryJedisCluster//BinaryJedisCluster的JedisClusterConnectionHandler屬性//里面有JedisClusterInfoCache,根據(jù)這一條繼承鏈,可以獲取到JedisClusterInfoCache//從而獲取slot和JedisPool直接的映射
MetaObject metaObject =SystemMetaObject.forObject(jc);
JedisClusterInfoCache cache= (JedisClusterInfoCache) metaObject.getValue("connectionHandler.cache");//保存地址+端口和命令的映射
Map> jedisPoolMap = new HashMap<>();
List keyList = null;
JedisPool currentJedisPool= null;
Pipeline currentPipeline= null;for(String key : keys){//計(jì)算哈希槽
int crc =JedisClusterCRC16.getSlot(key);//通過哈希槽獲取節(jié)點(diǎn)的連接
currentJedisPool =cache.getSlotPool(crc);//由于JedisPool作為value保存在JedisClusterInfoCache中的一個(gè)map對象中,每個(gè)節(jié)點(diǎn)的//JedisPool在map的初始化階段就是確定的和唯一的,所以獲取到的每個(gè)節(jié)點(diǎn)的JedisPool都是一樣//的,可以作為map的key
if(jedisPoolMap.containsKey(currentJedisPool)){
jedisPoolMap.get(currentJedisPool).add(key);
}else{
keyList= new ArrayList<>();
keyList.add(key);
jedisPoolMap.put(currentJedisPool, keyList);
}
}//保存結(jié)果
List res = new ArrayList<>();//執(zhí)行
for(Entry>entry : jedisPoolMap.entrySet()){try{
currentJedisPool=entry.getKey();
keyList=entry.getValue();//獲取pipeline
currentPipeline =currentJedisPool.getResource().pipelined();for(String key : keyList){
currentPipeline.get(key);
}//從pipeline中獲取結(jié)果
res =currentPipeline.syncAndReturnAll();
currentPipeline.close();for(int i=0; i
resMap.put(keyList.get(i), res.get(i)==null? null: res.get(i).toString());
}
}catch(Exception e) {
e.printStackTrace();return new HashMap<>();
}
}returnresMap;
}
}
總結(jié)
以上是生活随笔為你收集整理的list操作 rediscluster_Redis集群批量操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 内网镜像站_搭建私有YUM
- 下一篇: linux cmake编译源码,linu