redis 替换keys方案 scan

发布时间 2023-10-30 13:34:40作者: testgogogo

redis 替换keys方案


@Autowired
private RedisTemplate redisTemplate;
public Set<String> keyScan(String key) {
        //批量查询需要统计的数据
        Set<String> keys = (Set<String>) redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
            Set<String> keysTmp = new HashSet<>();
            Cursor<byte[]> cursor = connection
                    .scan(
                            new ScanOptions.ScanOptionsBuilder()
                                    .match(key + "*")
                                    .count(10000L)
                                    .build());
            while (cursor.hasNext()) {
                keysTmp.add(new String(cursor.next()));
            }
            return keysTmp;
        });
        return keys;
    }