zoukankan      html  css  js  c++  java
  • redis中scan和keys的区别

    scan和keys的区别

    redis的keys命令,通来在用来删除相关的key时使用,但这个命令有一个弊端,在redis拥有数百万及以上的keys的时候,会执行的比较慢,更为致命的是,这个命令会阻塞redis多路复用的io主线程,如果这个线程阻塞,在此执行之间其他的发送向redis服务端的命令,都会阻塞,从而引发一系列级联反应,导致瞬间响应卡顿,从而引发超时等问题,所以应该在生产环境禁止用使用keys和类似的命令smembers,这种时间复杂度为O(N),且会阻塞主线程的命令,是非常危险的。

    keys命令的原理就是扫描整个redis里面所有的db的key数据,然后根据我们的通配的字符串进行模糊查找出来。官网详细的介绍如下。

    https://redis.io/commands/KEYS

    取而代之的,如果需要查找然后删除key的需求,那么在生产环境我们应该使用scan命令,代替keys命令,同样是O(N)复杂度的scan命令,支持通配查找,scan命令或者其他的scan如SSCAN ,HSCAN,ZSCAN命令,可以不用阻塞主线程,并支持游标按批次迭代返回数据,所以是比较理想的选择。keys相比scan命令优点是,keys是一次返回,而scan是需要迭代多次返回。

    https://redis.io/commands/scan

    但scan命令的也有缺点,返回的数据有可能重复,需要我们在业务层按需要去重,scan命令的游标从0开始,也从0结束,每次返回的数据,都会返回下一次游标应该传的值,我们根据这个值,再去进行下一次的访问,如果返回的数据为空,并不代表没有数据了,只有游标返回的值是0的情况下代表结束。

    redis命令例子如下:

    scan 0 match my*key count 10000

    在Java项目里面,使用jedis执行scan命令的模板例子如下:

                   Jedis jedis = getJedis();               //存储返回的结果                Set<String> result=new HashSet<String>();                //设置查询的参数                ScanParams scanParams=new ScanParams().count(scanLimitSize).match(pattern);                //游标的开始                String cur=ScanParams.SCAN_POINTER_START;                do{                   //遍历每一批数据                    ScanResult<String> scan=jedis.scan(cur, scanParams);                    //得到结果返回                    List<String> scanResult =scan.getResult();                    result.addAll(scanResult);                    //获取新的游标                    cur=scan.getStringCursor();                //判断游标迭代是否结束                    }while (!cur.equals(ScanParams.SCAN_POINTER_START));                //返回结果                return result;

    java中使用redisTemplate实现

    • 方法一:通过 scan 先获取以“message:xxx:yyy:id: ”为 Key 前缀的所有完整的 Key,再通过获取到的 Key 拿所有的 Value
    /**
     * 通过 key 获取 value
     * <p>
     *    pattern:message:xxx:yyy:id: 
     *    limit:每次限制筛选的数量,不建议 Integer.MAX_VALUE
     */
    public List<String> assembleScanValues(String pattern, Long limit) {
        List<String> values = assembleScanKeys(pattern, limit);
        return redisTemplate.opsForValue().multiGet(values).stream().filter(StringUtils::isNotBlank).collect(toList());
    }
     
    /**
     * 组装 scan 的结果集
     */
    public List<String> assembleScanKeys(String pattern, Long limit) {
        HashSet<String> set = new HashSet<>();
        Cursor<String> cursor = scan(redisTemplate, pattern, limit);
        while (cursor.hasNext()) {
            set.add(cursor.next());
        }
        try {
            cursor.close();
        } catch (Exception e) {
            log.error("关闭 redis connection 失败");
        }
        return set.stream().map(String::valueOf).collect(toList());
    }
    /**
     * 自定义 redis scan 操作
     */
    private Cursor<String> scan(RedisTemplate redisTemplate, String pattern, Long limit) {
        ScanOptions options = ScanOptions.scanOptions().match(pattern).count(limit).build();
        RedisSerializer<String> redisSerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
        return (Cursor) redisTemplate.executeWithStickyConnection(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection redisConnection)
                    throws org.springframework.dao.DataAccessException {
                return new ConvertingCursor<>(redisConnection.scan(options), redisSerializer::deserialize);
            }
        });
    • 方法二:通过 scan 获取到 Key 的同时,去获取对应的 Value
    /**
     * 组装分布式缓存中的 value 值
     * <p>
     *    pattern:message:xxx:yyy:id: 
     *    limit:每次限制筛选的数量,不建议 Integer.MAX_VALUE
     */
    public List<String> assembleScanValues(String pattern, Long limit) {
        Set<String> valueSet = scan(redisTemplate, pattern, limit);
        return valueSet.stream().map(String::valueOf).collect(toList());
    }
     
    /**
      * 组装 scan 的结果集
      */
    private Set<String> scan(RedisTemplate redisTemplate, String pattern, Long limit) {
        return (Set<String>) redisTemplate.execute(new RedisCallback<Set<String>>() {
            @Override
            public Set<String> doInRedis(RedisConnection connection) throws DataAccessException {
                Set<String> valueSet = new HashSet<>();
                try (Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder()
                        .match(pattern).count(limit).build())) {
                    while (cursor.hasNext()) {
                        byte[] bytes = connection.get(cursor.next());
                        String value = String.valueOf(redisTemplate.getValueSerializer().deserialize(bytes));
                        valueSet.add(value);
                    }
                } catch (IOException e) {
                    log.error(String.format("get cursor close {%s}", e));
                }
                return valueSet;
            }
        });
    }

    参考及汇总自:https://qimok.cn/856.html https://cloud.tencent.com/developer/article/1440487
  • 相关阅读:
    line-block,white-space,overflow
    JS操作cookie
    C#的位运算
    小常识:变量的修饰符和DEMO
    JS等号的小注释
    关于谷歌浏览器的小常识
    P2568 GCD
    P2522 [HAOI2011]Problem b
    P3455 [POI2007]ZAP-Queries
    P1447 [NOI2010]能量采集
  • 原文地址:https://www.cnblogs.com/guanbin-529/p/12741638.html
Copyright © 2011-2022 走看看