Redis教程

RedisTemplate实现scan操作

本文主要是介绍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指令

这篇关于RedisTemplate实现scan操作的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!