当前位置:网站首页>在 RedisTemplate 中使用 scan
在 RedisTemplate 中使用 scan
2022-06-29 08:21:00 【lockie_zou】
SCAN 简介
SCAN 命令及其相关的 SSCAN 命令、 HSCAN 命令和 ZSCAN 命令都用于增量地迭代(incrementally iterate)一集元素(a collection of elements):
SCAN 和 KEYS 的区别
当 KEYS 命令被用于处理一个大的数据库时, 又或者 SMEMBERS 命令被用于处理一个大的集合键时, 它们会锁定 redis 库, 可能会阻塞服务器达数秒之久。在高并发下会导致请求大量堆积进而导致服务雪崩。有些公司在生产环境直接禁用 kyes * 命令。但是在 redis 服务器 key 的数量不大的情况下,使用 keys 也是没啥问题的。
SCAN 命令及其相关的 SSCAN 命令、 HSCAN 命令和 ZSCAN 命令都用于增量地迭代 ,它们每次执行都只会返回少量元素,不会阻塞服务器, 所以这些命令可以用于生产环境, 而不会出现像 KEYS 命令、 SMEMBERS 命令带来的问题。
SCAN 一样有它自己的问题:
- 因为是分段获取 key,所以它会多次请求 redis 服务器,这样势必取同样的 key,scan 耗时更长。
- 在对键进行增量式迭代的过程中, 键可能会被修改, 所以增量式迭代命令只能对被返回的元素提供有限的保证
/** * redis扩展工具 * * @author yuhao.wang3 * @since 2020/2/21 23:35 */ public abstract class RedisHelper { private static Logger logger = LoggerFactory.getLogger(RedisHelper.class); /** * scan 实现 * * @param redisTemplate redisTemplate * @param pattern 表达式,如:abc*,找出所有以abc开始的键 */ public static Set<String> scan(RedisTemplate<String, Object> redisTemplate, String pattern) { return redisTemplate.execute((RedisCallback<Set<String>>) connection -> { Set<String> keysTmp = new HashSet<>(); try (Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder() .match(pattern) .count(10000).build())) { while (cursor.hasNext()) { keysTmp.add(new String(cursor.next(), "Utf-8")); } } catch (Exception e) { logger.error(e.getMessage(), e); throw new RuntimeException(e); } return keysTmp; }); } }
边栏推荐
猜你喜欢

微积分学习

Core development board & debugger

The @dynamicmemberlookup and callasfunction features in swift implement the object transparent proxy function

闭关修炼(二十二)session和cookie原理

Chengtong network disk imitation blue playing network disk source code with video tutorial

抽象类、接口

Oracle subquery

Speech signal processing - Fundamentals (I): basic acoustic knowledge

机器人代码生成器之Robcogen使用教程

New paid Tarot calculation source code (with building tutorial)
随机推荐
晋升或汇报,你真的把事情讲清楚了吗?
2022年7月产品经理认证招生简章(NPDP)
首次触电,原来你是这样的龙蜥社区 | 龙蜥开发者说第8期
[redis] redis6 learning framework ideas and details
Debugging nocturnal simulator with ADB command
工作好多年,回忆人生--高中三年
Operating system product key viewing method
cokkie和session的区别
闭关修炼(二十一)Servlet生命周期、service方法源码分析、线程安全问题
图解SOC中的Timer(一):系统里有哪些Timer?
A high-frequency problem, three kinds of model thinking to solve this risk control problem
Mutex mutex
考研英语易混词整理【闪过】
15 things to learn in a year of internship in famous enterprises, so you can avoid detours.
Wechat applet development, how to add multiple spaces
2022 spring summer collection koreano essential reshapes the vitality of fashion
Is it safe for the top ten securities companies to open accounts? Is it reliable?
The sixth season of 2022 perfect children's model Qingyuan competition area audition came to a successful conclusion
How to gain profits from the operation of the points mall
开发小技巧-图片资源管理