当前位置:网站首页>Never use redis expired monitoring to implement scheduled tasks!
Never use redis expired monitoring to implement scheduled tasks!
2022-06-26 14:06:00 【Hollis Chuang】
Source of the article :https://c1n.cn/5n6fT
Catalog
Preface
Redis Overdue monitoring
RabbitMQ Dead letter
Time wheel
Conclusion
Preface
I read teacher a Niu's masterpiece a few days ago 《 Leader : Who uses the scheduled task to close the order , Get out of here !》 It is found that the scheme has several flaws , Here are some suggestions for discussion .
https://juejin.cn/post/6987233263660040206In the electricity supplier 、 Payment and other fields , There are often such scenes , The user gave up payment after placing an order , The order will be closed after the specified time period .
Careful, you must have found something like a treasure 、 A certain East has such logic , And the time is accurate , Error in 1s Inside , How did they achieve it ?
There are several general implementation methods :
Use RocketMQ、RabbitMQ、Pulsar Wait for the delayed delivery function of the message queue
Use Redisson Provided DelayedQueue
There are some schemes that are widely circulated but have fatal defects , Don't use it to implement deferred tasks :
Use Redis Expired monitoring for
Use RabbitMQ The dead letter line
Use non persistent time wheels
Redis Overdue monitoring
stay Redis The official Manual of keyspace-notifications: timing-of-expired-events It is clearly stated in :
Basically expired events are generated when the Redis server deletes the key and not when the time to live theoretically reaches the value of zero
Redis The implementation of automatic expiration is : Scheduled task offline scan and delete some expired keys ; Lazy checking for expiration when accessing keys and deleting expired keys .
Redis There is no guarantee that it will be deleted and sent an expiration notice at the set expiration time . actually , It is also common that the expiration notification is several minutes later than the set expiration time .
In addition, the key space notification is sent and forgotten (fire and forget) Strategy , Delivery is not guaranteed like message queuing . When a client subscribes to events, it will lose all the events distributed to it during disconnection .
This is a more “LOW” Solutions for , Please do not use .
Another big guy did the test 《 Don't rely too much on Redis Expired monitoring for 》, If you are interested in it, you can check it by yourself .
https://juejin.cn/post/6844904158227595271RabbitMQ Dead letter
Dead letter (Dead Letter) yes RabbitMQ A mechanism provided .
When a message meets one of the following conditions, it will become dead letter :
Message denied confirmation ( Such as channel.basicNack) And at this point requeue Property is set to false.
The message's lifetime in the queue exceeds the set TTL Time
The number of messages in the message queue has exceeded the maximum queue length
If dead letter queue is configured , Dead letter will be RabbitMQ Put it in the dead letter queue .
stay RabbitMQ The process of creating a dead letter queue in the :
Create a switch as a dead letter switch
Configure in the business queue x-dead-letter-exchange and x-dead-letter-routing-key, Set the switch in the first step as the dead letter switch of the service queue
Create a queue on the dead letter switch , And listen to this queue
Dead letter queue is designed to store messages that are not normally consumed , Easy to check and re deliver . The dead letter queue also does not guarantee the delivery time , Before the first message becomes a dead letter , The following messages will not be delivered as dead letters even if they are expired .
To solve this problem ,Rabbit The official launch of the delayed delivery plug-in rabbitmq-delayed-message-exchange , It is recommended to use the official plug-in for delay messages .
Here's a digression , Use Redis Overdue monitoring or RabbitMQ The dead letter queue uses Middleware in a way unexpected to the designer , There are some hidden dangers in this unexpected behavior , Such as lack of consistency and reliability assurance , Low throughput 、 Resource leakage, etc .
A famous example is that many people use Redis Of List As message queue , So that the last author can't read and write Disque And finally evolved into Redis Stream. Try not to abuse middleware at work , Do professional things with professional components .
Time wheel
Time wheel is an excellent data structure for timed tasks , However, the vast majority of time wheel implementations are pure memory without persistence .
After the process running the time wheel crashes, all the tasks in it will disappear , So I advise you to use it carefully .
| Redisson DelayQueue
Redisson DelayQueue It's based on Redis Zset Implementation of delay queue based on .DelayQueue One of them is called timeoutSetName Ordered set of , Of the elements score Is the delivery timestamp .
DelayQueue Can use regularly zrangebyscore Scan messages that have reached the delivery time , Then move them to the ready message list .
DelayQueue Guarantee Redis Messages are not lost without crashing , Try it when you don't have a better solution .
When the database index is well designed , The overhead of regularly scanning the database for outstanding orders is not as large as expected .
In the use of Redisson DelayQueue The method of scanning the database can be used as the compensation mechanism when waiting for timed task middleware , Avoid task loss caused by middleware failure .
Conclusion
The following points are summarized :
First of all, it is recommended to use RocketMQ、Pulsar And other message queues with scheduled delivery function .
When it is not convenient to obtain a professional message queue, you can consider using Redisson DelayQueue Based on Redis Delay queue scheme , But for Redis Design compensation protection mechanism in case of crash .
When you can't use Redisson DelayQueue You can consider using the time wheel . Because the time wheel restart is far better than Redis Restart frequently , Protection mechanisms such as regular library scanning are more important .
Never use Redis Overdue monitoring implements scheduled tasks .
End
My new book 《 In depth understanding of Java The core technology 》 It's on the market , After listing, it has been ranked in Jingdong best seller list for several times , At present 6 In the discount , If you want to start, don't miss it ~ Long press the QR code to buy ~

Long press to scan code and enjoy 6 A discount
Previous recommendation
What is the experience of writing a best seller
Please , Don't use pessimistic locks in high concurrency scenarios !
There is Tao without skill , It can be done with skill ; No way with skill , Stop at surgery
Welcome to pay attention Java Road official account

Good article , I was watching ️
边栏推荐
- Luogu p4145 seven minutes of God created questions 2 / Huashen travels around the world
- Tips for using nexys A7 development board resources
- 虫子 内存管理 上
- DataGrip配置的连接迁移
- 7.Consul服务注册与发现
- hands-on-data-analysis 第三单元 模型搭建和评估
- 创建一个自己的跨域代理服务器
- Use performance to see what the browser is doing
- Solutions to the failure of last child and first child styles of wechat applet
- Awk tools
猜你喜欢
随机推荐
It is better and safer to choose which securities company to open an account for flush stock
[MySQL from introduction to mastery] [advanced part] (II) representation of MySQL directory structure and tables in the file system
遍历指定目录获取当前目录下指定后缀(如txt和ini)的文件名
[path of system analyst] Chapter 15 double disk database system (database case analysis)
MySQL configuration improves data insertion efficiency
Formal parameters vs actual parameters
Ring queue PHP
In insect classes and objects
Awk tools
D中不用GC
7-2 a Fu the thief
输入文本自动生成图像,太好玩了!
Bucket of P (segment tree + linear basis)
es常用语法一
CVPR 2022文档图像分析与识别相关论文26篇汇集简介
Memory considerations under bug memory management
虫子 内存管理 下 内存注意点
Introduction to 26 papers related to CVPR 2022 document image analysis and recognition
9项规定6个严禁!教育部、应急管理部联合印发《校外培训机构消防安全管理九项规定》
Zero basics of C language lesson 8: Functions












