jedisCluster模式下使用scan命令来删除指定前缀的字符串

2023-12-20 20:11:13

因业务需要,需要对指定redis的前缀批量删除,如果直接使用keys 命令在数据量比较大的情况下会导致redis集群崩溃或者业务hang住。利用scan通过分页方式来拿到指定的key前缀,在进行相关数据的删除。

之前搜了网上很多文章,发现jedisCluster.getClusterNodes()在jedis的4.x版本获取的对象Map<String, ConnectionPool>,而不是Map<String, JedisPool>。针对这个情况进行代码改造

Connection jedisConnect = pool.getResource();

Jedis jedisNode = new Jedis(jedisConnect);

来获取jedisNode客户段,具体代码如下

public void delStringByScanV2(String keyPrefix) {

        ScanParams scanParams = new ScanParams().match(keyPrefix + "*").count(50);
        redisService.getJedis().getClusterNodes().values().stream()
        .forEach(pool -> {
            boolean done = false;
            String cursor = SCAN_POINTER_START;
            try (Connection jedisConnect = pool.getResource(); Jedis jedisNode = new Jedis(jedisConnect)) {
                while (!done) {
                    ScanResult<String> resp = jedisNode.scan(cursor, scanParams);

                    log.info("Key: " + resp.getResult() + ", Value: " + resp.getCursor() +",cluster: " + pool.getResource().toString());
                    //删除redis的key
                    resp.getResult().stream().map(key -> redisService.getJedis().del(key)).count();
                    cursor = resp.getCursor();
                    if (SCAN_POINTER_START.equals(cursor)) {
                        done = true;
                    }
                }
            }
        });
    }

其中getJedis返回的是?JedisCluster

 public JedisCluster getJedis() {
        if (jedis == null) {
            logger.info("Jedis connection is lost, need to reconnect " + redisNodes);
            createRedisConn();
        }
        return jedis;
    }

文章来源:https://blog.csdn.net/wppwpp1/article/details/135114977
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。