spring redis 使用笔记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qyvlik/article/details/79508920

spring redis 使用笔记

PS: 要按照实际业务场景以及实际瓶颈去优化工具的使用,而不是盲从优化建议。

SCAN

在 redis 中如果 key 的数量非常多的话,使用 KEYS命令可能非常慢,可以使用游标的方式增量是获取 key。

protected Set<String> keySet2(String pattern) {
    List<byte[]> rawBinaryKeys =
            redisTemplate.execute(new RedisCallback<List<byte[]>>() {
                @Override
                public List<byte[]> doInRedis(RedisConnection connection) throws DataAccessException {

                    Object nativeConnection = connection.getNativeConnection();

                    List<byte[]> binaryKeys = Lists.newArrayList();

                    Cursor<byte[]> cursor = connection.scan(ScanOptions.
                            scanOptions()
                            .count(10000)
                            .match(pattern)
                            .build());
                    while (cursor.hasNext()) {
                        byte[] key = cursor.next();
                        binaryKeys.add(key);
                    }


//                        try {
//                            cursor.close();               // The new version don not close here
//                        } catch (Exception e) {
//                        }

                    return binaryKeys;
                }
            });

    List keyList = SerializationUtils.deserialize(rawBinaryKeys, redisTemplate.getKeySerializer());

    return Sets.newHashSet(keyList);
}

参考

Redis基础、高级特性与性能调优

Redis Scan的使用方式以及Spring redis的坑

猜你喜欢

转载自blog.csdn.net/qyvlik/article/details/79508920