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; }
參考地址: