Home > Backend Development > PHP Tutorial > Delay queue implemented based on php and redis

Delay queue implemented based on php and redis

藏色散人
Release: 2023-04-04 16:44:01
Original
9723 people have browsed it

Based on redis, it is a delay queue that is highly available, easy to expand, easy to access, and stable in the production environment. Delay queue, as the name suggests, is a message queue with delay function. So, under what circumstances do I need such a queue?

Delay queue implemented based on php and redis

Recommended tutorial: "redis video tutorial"

1. Background

Let’s take a look at the business scenario first:

1. Send a recall notice 3 days before the membership expires

2. After the order payment is successful, check whether the downstream links are all connected after 5 minutes Normal, for example, after a user purchases a membership, whether all membership statuses are set successfully

3. How to regularly check whether an order in refund status has been successfully refunded?

4. If the notification fails, the notification will be repeated in 1, 3, 5, and 7 minutes until the other party replies?

Usually the simplest and most direct way to solve the above problems is to scan the meter regularly.

The problems with table scanning are:

1. The table scanning is connected to the database for a long time. In the case of large quantities, the connection is prone to abnormal interruption, which requires more exception handling and the program High robustness requirements

2. When the amount of data is large, the delay is high and the processing cannot be completed within the regulations, which affects the business. Although multiple processes can be started for processing, this will bring additional maintenance costs. , cannot be fundamentally solved.

3. Each business must maintain its own table scanning logic. When the business grows more and more, it is found that the logic of the table scanning part will be developed repeatedly, but it is very similar

The delay queue can solve the above needs very well

2. Research

We investigated some open source solutions on the market, as follows:

1. Youzan Technology: Only principles, no open source code

2. github personal: https://github.com/ouqiang/delay-queue

1.基于redis实现,redis只能配置一个,如果redis挂了整个服务不可用,可用性差点
2.消费端实现的是拉模式,接入成本大,每个项目都得去实现一遍接入代码
3.在star使用的人数不多,放在生产环境,存在风险,加之对go语言不了解,出了问题难以维护
Copy after login

3. SchedulerX-Alibaba open source: Very powerful, but operation and maintenance is complex, relies on many components, and is not lightweight enough

4.RabbitMQ-delayed task: It does not have a delay function, so it needs to be implemented by itself with the help of a feature. Moreover, the company has not deployed this queue. It is a bit expensive to deploy a separate one to make a delay queue, and it is also expensive. Special operation and maintenance is required for maintenance. Currently, the team does not support

Basically, for the above reasons, I plan to write one myself. I usually use PHP mostly. The basic redis zset structure of the project is used as storage and is implemented in PHP language. For the implementation principle, please refer to Like the team: https://tech.youzan.com/queuing_delay/

The entire delay queue mainly has 4 parts:

1.JobPool is used to store all jobs meta information.

2.DelayBucket is a set of ordered queues with time as the dimension, used to store all jobs that need to be delayed (only Job IDs are stored here).

3.Timer is responsible for scanning each Bucket in real time and placing Jobs whose delay time is greater than or equal to the current time into the corresponding Ready Queue.

4.ReadyQueue stores Jobs in the Ready state (only JobId is stored here) for consumption by consumer programs.

Delay queue implemented based on php and redis

Message structure Each Job must contain the following attributes:

1.topic: Job type. It can be understood as a specific business name.

2.id: The unique identifier of the Job. Used to retrieve and delete specified Job information.

3.delayTime: jod delayed execution time, 13-digit timestamp

4.ttr (time-to-run): Job execution timeout.

5.body: The content of the Job, for consumers to do specific business processing, stored in json format.

For the same type of topic delaytime, ttr is generally fixed, and the job properties can be simplified

1.topic: Job type. It can be understood as a specific business name

2.id: the unique identifier of the Job. Used to retrieve and delete specified Job information.

3.body: The content of the Job, for consumers to do specific business processing, stored in json format.

delaytime, ttr are configured in the topicadmin background

3. Target

  • Light Magnitude: It can be run directly with less PHP extensions, without introducing network frameworks, such as swoole, workman and the like

  • ##stability: Using the master-work architecture, the master does not do business processing, but is only responsible for managing the child process. When the child process exits abnormally, it will be automatically pulled up

  • Availability:

1. Supports multi-instance deployment, each instance is stateless, and the failure of one instance will not affect the service

2. Supports the configuration of multiple redis, and the failure of one redis will only affect the service Partial messages

3. The business party has easy access, and only needs to fill in the relevant message type and callback interface in the background

  • Extensibility: When consuming When there is a bottleneck in the process, you can configure to increase the number of consuming processes. When there is a bottleneck in writing, you can increase the number of instances. The writing performance can be linearly improved

  • Real-time performance : A certain time error is allowed.

  • 支持消息删除:业务使用方,可以随时删除指定消息。

  • 消息传输可靠性:消息进入到延迟队列后,保证至少被消费一次。

  • 写入性能:qps>1000+

四、架构设计与说明

总体架构

Delay queue implemented based on php and redis

采用master-work架构模式,主要包括6个模块:

1.dq-mster: 主进程,负责管理子进程的创建,销毁,回收以及信号通知

2.dq-server: 负责消息写入,读取,删除功能以及维护redis连接池

3.dq-timer-N: 负责从redis的zset结构中扫描到期的消息,并负责写入ready 队列,个数可配置,一般2个就行了,因为消息在zset结构是按时间有序的

4.dq-consume-N: 负责从ready队列中读取消息并通知给对应回调接口,个数可配置

5.dq-redis-checker: 负责检查redis的服务状态,如果redis宕机,发送告警邮件

6.dq-http-server: 提供web后台界面,用于注册topic

五、模块流程图

消息写入:

Delay queue implemented based on php and redis

timer查找到期消息:

Delay queue implemented based on php and redis

consumer消费流程:

Delay queue implemented based on php and redis

六、部署

环境依赖:PHP 5.5+ 安装sockets,redis,pcntl,pdo_mysql 拓展

ps: 熟悉docker的同学可以直接用镜像: shareclz/php7.2.14 里面包含了所需拓展

step1:安装数据库用于存储一些topic以及告警信息

执行:

mysql> source dq.sql
Copy after login

step2:在DqConfg.文件中配置数据库信息: DqConf::$db

step3: 启动http服务

在DqConf.php文件中修改php了路径 $phpBin

命令:

php DqHttpServer.php --port 8088
Copy after login

访问:http://127.0.0.1:8088,出现配置界面

Delay queue implemented based on php and redis

redis信息格式:host:port:auth 比如 127.0.0.1:6379:12345

step4:配置告信息(比如redis宕机)

Delay queue implemented based on php and redis

step5:注册topic

Delay queue implemented based on php and redis

重试标记说明:

1.接口返回为空默认重试
2.满足指定返回表达会重试,res表示返回的json数组,比如:
回调接口返回json串:{"code":200,"data":{"status":2,"msg":"返回失败"}},重试条件可以这样写
    {res.code}!=200 
    {res.code}!=200 && {res.data.status}!=2 
    {res.code}==200 && {res.data.status}==2 || {res.data.msg}=='返回失败'
Copy after login

Delay queue implemented based on php and redis

step6:启动服务进程:

php DqInit.php --port 6789 &
Copy after login

执行 ps -ef | grep dq 看到如下信息说明启动成功

Delay queue implemented based on php and redis

step7: 写入数据,参考demo.php

step8:查看日志

默认日志目录在项目目录的logs目录下,在DqConf.php修改$logPath

1.请求日志:request_ymd.txt

2.通知日志:notify_ymd.txt

3.错误日志:err_ymd.txt

step9:如果配置文件有改动

1.系统会自动检测配置文件新,如果有改动,会自动退出(没有找到较好的热更新的方案),需要重启,可以在crontab里面建个任务,1分钟执行一次,程序有check_self的判断

2.优雅退出命令: master检测侦听了USR2信号,收到信号后会通知所有子进程,子进程完成当前任务后会自动退出

ps -ef | grep dq-master| grep -v grep | head -n 1 | awk '{print $2}' | xargs kill -USR2
Copy after login

七、性能测试

需要安装pthreads拓展:

测试原理:使用多线程模拟并发,在1s内能成功返回请求成功的个数

php DqBench  concurrency  requests
concurrency:并发数
requests: 每个并发产生的请求数
测试环境:内存 8G ,8核cpu,2个redis和1个dq-server 部署在一个机器上,数据包64字节
qps:2400
Copy after login

八、值得一提的性能优化点:

1.redis multi命令:将多个对redis的操作打包成一个减少网络开销

2.计数的操作异步处理,在异步逻辑里面用函数的static变量来保存,当写入redis成功后释放static变量,可以在redis出现异常时计数仍能保持一致,除非进程退出

3.内存泄露检测有必要: 所有的内存分配在底层都是调用了brk或者mmap,只要程序只有大量brk或者mmap的系统调用,内存泄露可能性非常高 ,检测命令:

strace -c -p pid | grep -P 'mmap| brk'
Copy after login

4.检测程序的系统调用情况:strace -c -p pid ,发现某个系统函数调用是其他的数倍,可能大概率程序存在问题

推荐参考:《Redis命令操作中文手册

九、异常处理

1.如果调用通知接口在超时时间内,没有收到回复认为通知失败,系统会重新把数据放入队列,重新通知,系统默认最大通知10次(可以在Dqconf.php文件中修改$notify_exp_nums)通知间隔为2n+1,比如第一次1分钟,通知失败,第二次3分钟后,直到收到回复,超出最大通知次数后系统自动丢弃,同时发邮件通知

2.线上redis每隔1s持久化一次,存在丢失1s数据的情况,出现这种情况可以对比request_ymd.txt和notify_ymd.txt日志手动恢复过来

3.redis宕机通知:

Delay queue implemented based on php and redis

ps:网络抖动在所难免,通知接口如果涉及到核心的服务,一定要保证幂等!!

十、线上情况

线上部署了两个实例每个机房部一个,4个redis共16G内存作存储,服务稳定运行数月,各项指标均符合预期

主要接入业务:

订单10分钟召回通知

调用接口超时或者失败时做补偿

会员过期前3天召回通知

十一、不足与展望

1.由于团队使用的镜像缺少libevent拓展,所以dq-server基于select模型,并发高的场景下性能存在瓶颈,后续可以改为基于libevent事件模型,提升并发性能

2.timer和consumer目前是采用多进程来做的,这个粒度感觉有点粗,可以考虑使用多线程模式,并且支持动态创建线程数来提高consumer的性能,最大程度保证消费及时

3.dq-server与redis是同步调用,这也是性能的瓶颈点,计划基于swoole_redis来异步处理

[更新]

一、测试网络框架切换到swoole和使用异步swoole_redis带来的性能改变情况 把dqserver的主要逻辑基于swoole重新写了一遍,测试机(内存4G,cpu个数4)

启动sever:

php test_swoole_server.php 9055
Copy after login

压测:

php test_swoole_bench.php 100 56
Copy after login

结果:

1.原生dq-server: qps 2200

2.基于swoole&swoole_redis: qps 5600

写入性能提升:2.6倍

引入swoole性能提升比较明显,不过目前暂时不打算把server改为swoole的方式,主要基于以下考虑

1.目前我们线上单个示例的qps3000,部署了两个,6000ps可以满足我们大部分场景

2.目前对swoole处于了解的过程

二、新增队列消费分优先级(高,中,低3级),高优任务可以优先消费 消费比例在DqConf::$priorityConfig配置,默认按照5:3:2的比例消费

推荐相关redis视频教程:

燕十八redis视频教程

传智播客redis基础视频教程

黑马云课堂NoSQL之Redis技术视频教程

NoSql-redis基础视频教程

麦子学院深入浅出 redis 视频教程

感谢PHP中文网热心网友的投稿,其GitHub地址为:https://github.com/chenlinzhong/php-delayqueue

The above is the detailed content of Delay queue implemented based on php and redis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template