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

public static void delKeys(HostAndPort hostAndPort, String keysPattern) {
        Map clusterNodes = getJedisCluster(hostAndPort).getClusterNodes();

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

                if (keys.size() > 0) {
                    Map> 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> integerListEntry : map.entrySet()) {
                        jedis.del(integerListEntry.getValue().toArray(new String[integerListEntry.getValue().size()]));
                    }
                }
            }
        }
    }

你可能感兴趣的:(redis)