zoukankan      html  css  js  c++  java
  • 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指令

    作者:小念
    本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
  • 相关阅读:
    单例模式
    json 格式
    axios 获取不到数据错误
    sprint test 添加事务回滚机制
    springboot An incompatible version [1.1.32] of the APR based Apache Tomcat Native library is installed, while Tomcat requires version [1.2.14]
    spring boot 启动之后404
    废了
    tomcat 部署项目到服务器
    Druid 介绍及配置
    jq 全选
  • 原文地址:https://www.cnblogs.com/kiko2014551511/p/15411048.html
Copyright © 2011-2022 走看看