当前位置:网站首页>How Redis handles concurrent access
How Redis handles concurrent access
2022-07-31 15:54:00 【Juggernaut without trace】
携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第5天,点击查看活动详情
前言
项目中经常会遇到这种场景,我们需要先将RedisData is read locally,然后进行修改,Write the data back after the modification is completeRedis,这种读取-修改-写回操作,我们称之为RMW操作.当有多个客户端对同一份数据执行RMW操作的话,Redis如何保证RMW操作涉及的代码以原子性方式执行?
原子性操作
RedisThe atomic operation of is a lock-free operation,That is, concurrency control can be guaranteed,It also reduces the impact of the system on concurrent performance,
单命令模式
把RedisMultiple operations are implemented into one operation,That is, single command mode.
Redis提供了INCR/DECR命令,Data can be added value/减值操作,而且它们本身就是单个命令操作,Redis单线程模式,Mutually exclusive when executing commands.
示例说明
public Long getIncrNumber(String key,long alive)
{
RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
Long incrNum = entityIdCounter.getAndIncrement();
if (null == incrNum || incrNum.longValue()==0)
{
entityIdCounter.expire(alive,TimeUnit.MILLISECONDS);
incrNum = entityIdCounter.getAndIncrement();
}
return incrNum;
}
复制代码说明:采用Reids的INCR命令,如果不存在的key则设置过期时间,如果keyIf it exists, the increment operation is performed and returned.So if we executeRMWWhen the operation performs related increment or decrement operations,Redis提供的INCR和DECYCommands can guarantee concurrency control.
多命令模式
When we are not performing simple addition and subtraction operations,It is more complex logical judgment or other operations,Redis是无法保证原子性,So multiple operations need to be written to oneLua脚本中,Redis会把Lua脚本作为一个整体执行,在执行过程中不会被其他命令打断,This ensures the atomicity of the operation.
lua简介
Lua是一种轻量小巧的脚本语言,用标准C语言编写并以源代码形式开放, 其设计目的是为了嵌入应用程序中,从而为应用程序提供灵活的扩展和定制功能.
示例说明
The interface performs current limiting operation,同一用户3No repeated access within seconds,我们可以通过lua脚本来实现.
local key = KEYS[1]
local count = tonumber(ARGV[1])
local time = tonumber(ARGV[2])
local current = redis.call('get', key)
if current and tonumber(current) > count then
return tonumber(current)
end
current = redis.call('incr', key)
if tonumber(current) == 1 then
redis.call('expire', key, time)
end
return tonumber(current)
复制代码说明:key、count、timefor three incoming parameters,分别代表Redis的key、times and expiration times.通过get获取key对应的值,The value obtained is the number of times the interface is accessed within a time period,If it is the first visit, it will return null,At this point need to be currentkey进行自增1操作,If returned as a number,Then you need to determine whether the returned number has exceededcout值,If it exceeds, it means that the current limit has been exceeded,直接返回.
建议
- 1.编写luaScripts should not perform complex and time-consuming calculation logic,否则执行lua时间过长,会导致Redis主线程阻塞.
- 2.luaScript as simple as possible,Don't put all operations into itlua脚本中执行,这样会导致Redis执行脚本的时间增加,同时也会降低Redis的并发性能.
事务
About transaction guarantees atomicity,采用的watchThe principle of the command is similar to the implementation principle of optimistic locking,详情可以参考juejin.cn/post/712582… 文章,This article will not elaborate.
加锁
关于Redis的分布式锁的实现,Subsequent chapters describe in detail.Locking in a high concurrency environment can ensure correctness,But it also brings other problems:
- Too many locking operations will reduce the concurrent access performance of the system
- RedisThe client needs to be locked,需要使用分布式锁,而分布式锁实现复杂,增加复杂度.
总结
This article explains targeting concurrent accessRedisHow to guarantee atomic operation,针对不同的业务场景,选择合适的方案,如有疑问请随时反馈.
边栏推荐
- Codeforces Round #796 (Div. 2)(A-D)
- Website vulnerability repair service provider's analysis of unauthorized vulnerability
- MySQL基础篇【单行函数】
- Internet banking stolen?This article tells you how to use online banking safely
- type of timer
- "Autumn Recruitment Series" MySQL Interview Core 25 Questions (with answers)
- Kubernetes common commands
- Tencent Cloud Deployment----DevOps
- C language "the third is" upgrade (mode selection + AI chess)
- How useful is four-quadrant time management?
猜你喜欢

【Meetup预告】OpenMLDB+OneFlow:链接特征工程到模型训练,加速机器学习模型开发

01 邂逅typescript,环境搭建

工程水文学复习资料

How useful is four-quadrant time management?

mongo enters error

11 pinia使用

After Grafana is installed, the web opens and reports an error

全新宝马3系上市,安全、舒适一个不落

Why is the field of hacking almost filled with boys?

t-sne 数据可视化网络中的部分参数+
随机推荐
ASP.NET Core generates continuous Guid
ASP.NET Core 产生连续 Guid
Kubernetes常用命令
【Meetup预告】OpenMLDB+OneFlow:链接特征工程到模型训练,加速机器学习模型开发
Character pointer assignment [easy to understand]
Codeforces Round #796 (Div. 2) (A-D)
字符指针赋值[通俗易懂]
Getting Started with TextBlock Control Basic Tools Usage, Get Started
BGP综合实验(建立对等体、路由反射器、联邦、路由宣告及聚合)
arm按键控制led灯闪烁(嵌入式按键实验报告)
Why is the field of hacking almost filled with boys?
Implementing DDD based on ABP
6-22 Vulnerability exploit - postgresql database password cracking
字符串反转的实现方法总结「建议收藏」
mongo enters error
Graham‘s Scan法求解凸包问题
定时器的类型
7、常见面试口语提问问题汇总
what exactly is json (c# json)
Codeforces Round #796 (Div. 2)(A-D)