RedisTemplate实现scan操作

keys 的操作会导致数据库暂时被锁住,其他的请求都会被堵塞;业务量大的时候会出问题

当需要扫描key,匹配出自己需要的key时,可以使用 scan 命令

 

java代码实现如下:

/**
     * 使用scan遍历key
     * 为什么不使用keys 因为Keys会引发Redis锁,并且增加Redis的CPU占用,特别是数据庞大的情况下。这个命令千万别在生产环境乱用。
   * 支持redis单节点和集群调用  *
@param matchKey * @return */ public Set<String> scanMatch(String matchKey) { Set<String> keys = new HashSet(); RedisConnectionFactory connectionFactory = redisTemplate.getConnectionFactory(); RedisConnection redisConnection = connectionFactory.getConnection(); Cursor<byte[]> scan = null; if(redisConnection instanceof JedisClusterConnection){ RedisClusterConnection clusterConnection = connectionFactory.getClusterConnection(); Iterable<RedisClusterNode> redisClusterNodes = clusterConnection.clusterGetNodes(); Iterator<RedisClusterNode> iterator = redisClusterNodes.iterator(); while (iterator.hasNext()) { RedisClusterNode next = iterator.next(); scan = clusterConnection.scan(next, ScanOptions.scanOptions().match(matchKey).count(Integer.MAX_VALUE).build()); while (scan.hasNext()) { keys.add(new String(scan.next())); } try { if(scan !=null){ scan.close(); } } catch (IOException e) { log.error("scan遍历key关闭游标异常",e); } } return keys; } if(redisConnection instanceof JedisConnection){ scan = redisConnection.scan(ScanOptions.scanOptions().match(matchKey).count(Integer.MAX_VALUE).build()); while (scan.hasNext()){ //找到一次就添加一次 keys.add(new String(scan.next())); } try { if(scan !=null){ scan.close(); } } catch (IOException e) { log.error("scan遍历key关闭游标异常",e); } return keys; } return keys; }

 

 

 

 

参考地址:

Spring RedisTemplate实现scan操作,毕竟keys不安全

在RedisTemplate中使用scan代替keys指令

posted @ 2021-10-15 14:52  harara  阅读(7144)  评论(0编辑  收藏  举报