Bootstrap

java方法扫描redis缓存KEY的指定值方法

java方法扫描redis缓存KEY的指定值方法
1.实现方法

 public Set<String> scan(String pattern, RedisTemplate template) {
        return (Set<String>) template.execute((RedisCallback<Set<String>>) connection -> {
            Set<String> keys = new HashSet<>();
            JedisCluster cluster = (JedisCluster) connection.getNativeConnection();
            Collection<JedisPool> pools = cluster.getClusterNodes().values();
            for (JedisPool pool : pools) {
                Jedis resource = pool.getResource();
                ScanParams scanParams = new ScanParams();
                scanParams.match(pattern + "*");
                scanParams.count(1000);
                ScanResult<String> scan = resource.scan("0", scanParams);
                while (null != scan.getCursor()) {
                    keys.addAll(scan.getResult());
                    if (StringUtils.equals("0", scan.getCursor())) {
                        break;
                    }
                    scan = resource.scan(scan.getCursor(), scanParams);
                }
                resource.close();
            }
            return keys;
        });
    }

2.调用样例

 @Autowired
 RedisTemplate redisTemplate;

 @Override
 public List<String> scanCacheKey(String key) {
      
      Set<String> scan = scan(key, redisTemplate);
      return new ArrayList<>(scan);
  }
  

;