RedisTemplate使用SCAN命令扫描key替代KEYS避免redis服务器阻塞,无坑!完美解决方案

先来鄙视下博客上很多人不懂瞎几把乱说还有大量转载误导群众,本文原创亲自验证方案。

话不多说先上代码,拿走即用。

long start = System.currentTimeMillis();
        //需要匹配的key
        String patternKey = "pay:*";
        ScanOptions options = ScanOptions.scanOptions()
                //这里指定每次扫描key的数量(很多博客瞎说要指定Integer.MAX_VALUE,这样的话跟        keys有什么区别?)
                .count(10000)
                .match(patternKey).build();
        RedisSerializer redisSerializer = (RedisSerializer) redisTemplate.getKeySerializer();
        Cursor cursor = (Cursor) redisTemplate.executeWithStickyConnection(redisConnection -> new ConvertingCursor<>(redisConnection.scan(options), redisSerializer::deserialize));
        List result = new ArrayList<>();
        while(cursor.hasNext()){
            result.add(cursor.next().toString());
        }
        //切记这里一定要关闭,否则会耗尽连接数。报Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisException: Could not get a 
        cursor.close();
        log.info("scan扫描共耗时:{} ms key数量:{}",System.currentTimeMillis()-start,result.size());

 

你可能感兴趣的:(javase,javaWeb,springboot)