1. 程式人生 > >redis cluster 模式如何批量刪除指定字首的key

redis cluster 模式如何批量刪除指定字首的key

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()]));
                    }
                }
            }
        }
    }