您的位置:首页 > 数据库 > Redis

redis cluster 模式如何批量删除指定前缀的key

2017-08-16 10:19 696 查看
public static void delKeys(HostAndPort hostAndPort, String keysPattern) {
Map<String, JedisPool> clusterNodes = getJedisCluster(hostAndPort).getClusterNodes();

for (Map.Entry<String, JedisPool> entry : clusterNodes.entrySet()) {
Jedis jedis = entry.getValue().getResource();
if (!jedis.info("replication").contains("role:slave")) {
Set<String> keys = jedis.keys(keysPattern);

if (keys.size() > 0) {
Map<Integer, List<String>> map = new HashMap<>(6600);
for (String key : keys) {
int slot = JedisClusterCRC16.getSlot(key);//cluster模式执行多key操作的时候,这些key必须在同一个slot上,不然会报:JedisDataException: CROSSSLOT Keys in request don't hash to the same slot
//按slot将key分组,相同slot的key一起提交
if (map.containsKey(slot)) {
map.get(slot).add(key);
} else {
map.put(slot, Lists.newArrayList(key));
}
}
for (Map.Entry<Integer, List<String>> integerListEntry : map.entrySet()) {
jedis.del(integerListEntry.getValue().toArray(new String[integerListEntry.getValue().size()]));
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: