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指令

    作者:小念
    本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
  • 相关阅读:
    qt5--数据类型转换
    qt5-QWidget坐标系统和大小和展示区域
    qt5---布局
    qt5-信号和槽
    tomcat中文请求乱码问题
    centos安装ab测试工具
    golang学习之go简单博客应用
    nodejs的jsonrpc调用
    centos下mongodb安装
    使用connect-multiparty限制nodejs图片上传
  • 原文地址:https://www.cnblogs.com/kiko2014551511/p/15411048.html
Copyright © 2011-2022 走看看