springboot redis cluster模式 scan操作

springboot1.x

1. rediscluster模式是不可以直接scan操作的,我们可以拿到所有的节点,通过遍历所有节点的方式去scan

public Set scan(String key) {
    return redisTemplate.execute((RedisCallback>) connection -> {
        Set keys = new HashSet<>();

        JedisCluster cluster = (JedisCluster) connection.getNativeConnection();
        Collection pools = cluster.getClusterNodes().values();

        for (JedisPool pool : pools) {
            Jedis resource = pool.getResource();
            ScanParams scanParams = new ScanParams();
            scanParams.match(key + "*");
            scanParams.count(DEFAULT_COUNT);
            ScanResult scan = resource.scan("0", scanParams);
            while (null != scan.getStringCursor()) {
                keys.addAll(scan.getResult());
                if (StringUtils.equals("0", scan.getStringCursor())) {
                    break;
                }
                scan = resource.scan(scan.getStringCursor(), scanParams);
            }
            resource.close();
        }

        return keys;
    });
}

2. redis cluster模式下使用hash tag的方式来直接scan;当key包含{}的时候,仅会对{}中的内容进行hash而不会对整个key

public Set scanHashTag(String key) {
    return redisTemplate.execute((RedisCallback>) connection -> {
        Set keys = new HashSet<>();

        JedisCluster cluster = (JedisCluster) connection.getNativeConnection();

        ScanParams scanParams = new ScanParams();
        scanParams.match(key + "*");
        scanParams.count(DEFAULT_COUNT);
        ScanResult scan = cluster.scan("0", scanParams);
        while (null != scan.getStringCursor()) {
            keys.addAll(scan.getResult());
            if (StringUtils.equals("0", scan.getStringCursor())) {
                break;
            }
            scan = cluster.scan(scan.getStringCursor(), scanParams);
        }

        return keys;
    });
}

springboot2.x

1. 由于底层实现是lettuce

public Set scan2(String matchKey) {
    return redisTemplate.execute((RedisCallback>) connection -> {
        Set keys = new HashSet<>();
        Cursor cursor = connection.scan(new ScanOptions.ScanOptionsBuilder()
                .match(matchKey + "*").count(DEFAULT_COUNT).build());
        while (cursor.hasNext()) {
            keys.add(new String(cursor.next()));
        }
        return keys;
    });
}

 

你可能感兴趣的:(springboot redis cluster模式 scan操作)