php redis延迟队列,easyswoole 基于Redis组件实现延迟队列

EasySwoole 基于Redis组件实现延迟队列

介绍

在用户要支付订单的时候,如果超过30分钟未支付,会把订单关掉。当然我们可以做一个定时任务,每个一段时间来扫描未支付的订单,如果该订单超过支付时间就关闭,但是在数据量小的时候并没有什么大的问题,但是数据量一大轮训数据库的方式就会变得特别耗资源。当面对千万级、上亿级数据量时,本身写入的IO就比较高,导致长时间查询或者根本就查不出来,更别说分库分表以后了。

使用延迟队列解决的痛点无非是

实现了数据延迟

数据摊开(仔细去理解)

知识点

案例

生成订单id ---> 扔到延迟队列 ---> 延迟队列消费进程不停获取30分钟前的订单满足条件的订单 ---> 处理订单

直接上代码

EasySwooleEvent.php 注册redis连接池、注册延迟队列消费进程

namespace EasySwoole\EasySwoole;

use App\Process\Consumer;

use EasySwoole\EasySwoole\Swoole\EventRegister;

use EasySwoole\EasySwoole\AbstractInterface\Event;

use EasySwoole\Http\Request;

use EasySwoole\Http\Response;

use EasySwoole\Pool\Manager;

use EasySwoole\Redis\Config\RedisConfig;

use App\RedisPool\RedisPool;

use EasySwoole\Pool\Config;

class EasySwooleEvent implements Event

{

public static function initialize()

{

// TODO: Implement initialize() method.

date_default_timezone_set('Asia/Shanghai');

}

public static function mainServerCreate(EventRegister $register)

{

//TODO:: 注册redis连接池

$config = new Config();

$redisConfig1 = new RedisConfig([

'host' => '127.0.0.1',

'port' => '6379'

]);

// 这里的redis连接池看文档配吧

Manager::getInstance()->register(new RedisPool($config,$redisConfig1),'redis');

//TODO:: 延迟队列消费进程

$processConfig= new \EasySwoole\Component\Process\Config();

$processConfig->setProcessName('testProcess');

\EasySwoole\Component\Process\Manager::getInstance()->addProcess(new Consumer($processConfig));

}

public static function onRequest(Request $request, Response $response): bool

{

// TODO: Implement onRequest() method.

return true;

}

public static function afterRequest(Request $request, Response $response): void

{

// TODO: Implement afterAction() method.

}

}

扔到延迟队列

namespace App\HttpController;

use EasySwoole\Http\AbstractInterface\Controller;

use EasySwoole\Pool\Manager;

class Index extends Controller

{

function index()

{

/** @var $redis \EasySwoole\Redis\Redis*/

$orderId = date('YmdHis', time());

$redis = Manager::getInstance()->get('redis')->getObj();

$res = $redis->zAdd('delay_queue_test1', time(), $orderId);

if ($res) {

$this->writeJson(200, '订单添加成功:'.$orderId);

}

}

}

延迟队列消费进程

namespace App\Process;

use EasySwoole\Component\Process\AbstractProcess;

use EasySwoole\Pool\Manager;

use Swoole\Coroutine;

class Consumer extends AbstractProcess {

protected function run($arg)

{

go(function (){

while (true) {

//TODO:: 拿到redis

/** @var $redis \EasySwoole\Redis\Redis*/

$redis = Manager::getInstance()->get('redis')->defer();

//TODO:: 从有序集合中拿到三秒(模拟30分钟)以前的订单

$orderIds = $redis->zRangeByScore('delay_queue_test1', 0, time()-3, ['withscores' => TRUE]);

if (empty($orderIds)) {

Coroutine::sleep(1);

continue;

}

//TODO::拿出后立马删除

$redis->zRem('delay_queue_test1', ...$orderIds);

foreach ($orderIds as $orderId)

{

var_dump($orderId);

//TODO::判断此订单30分钟后,是否仍未完成,做相应处理

}

}

});

}

}

测试

请求index/index 投递订单到延迟队列

➜ ~ curl 127.0.0.1:9501/index/index

{"code":200,"result":"订单添加成功:20200422004046","msg":null}%

等3s看终端是否输出

➜ easyswoole php easyswoole start

______ _____ _

| ____| / ____| | |

| |__ __ _ ___ _ _ | (___ __ __ ___ ___ | | ___

| __| / _` | / __| | | | | \___ \ \ \ /\ / / / _ \ / _ \ | | / _ \

| |____ | (_| | \__ \ | |_| | ____) | \ V V / | (_) | | (_) | | | | __/

|______| \__,_| |___/ \__, | |_____/ \_/\_/ \___/ \___/ |_| \___|

__/ |

|___/

main server SWOOLE_WEB

listen address 0.0.0.0

listen port 9501

ip@en0 192.168.43.57

worker_num 8

reload_async true

max_wait_time 3

pid_file /Users/xx/sites/easyswoole/Temp/pid.pid

log_file /Users/xx/sites/easyswoole/Log/swoole.log

user xx

daemonize false

swoole version 4.4.15

php version 7.2.18

easy swoole 3.3.7

develop/produce develop

temp dir /Users/xx/sites/easyswoole/Temp

log dir /Users/xx/sites/easyswoole/Log

string(14) "20200422004046"

总结

这只是一个思路,大家可以根据实际业务做不同调整

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Redis延迟队列可以通过利用Redis的zset和list数据结构来实现。下面是一个简单的实现方式: 1. 创建一个JobPool,用来存放所有Job的元信息。可以使用Hash数据结构来存储每个Job的详细信息,例如Job的ID、执行时间、参数等。 2. 创建一组以时间为维度的DelayBucket,用来存放所有需要延迟的Job。可以使用zset数据结构来存储Job的ID,并将Job的执行时间作为分数,以便按照时间顺序进行排序。 3. 创建一个Timer,负责实时扫描各个Bucket,并将延迟时间到达的Job从DelayBucket中取出,放入ReadyQueue中等待执行。 4. 创建一个ReadyQueue,用来存放已经到达执行时间的Job。可以使用list数据结构来存储Job的ID,按照先进先出的顺序进行执行。 5. 当需要添加一个延迟Job时,将Job的元信息存入JobPool,并将Job的ID添加到对应的DelayBucket中。 6. Timer定时扫描各个Bucket,将延迟时间到达的Job从DelayBucket中取出,放入ReadyQueue中。 7. 从ReadyQueue中取出Job的ID,根据Job的ID从JobPool中获取Job的详细信息,并执行相应的操作。 下面是一个简单的Python代码示例,演示了如何使用Redis实现延迟队列: ```python import redis import time # 连接Redis r = redis.Redis(host='localhost', port=6379, db=0) # 添加延迟Job def add_delayed_job(job_id, execute_time): # 将Job的元信息存入JobPool r.hset('JobPool', job_id, execute_time) # 将Job的ID添加到对应的DelayBucket中 r.zadd('DelayBucket', {job_id: execute_time}) # Timer定时扫描Bucket def timer_scan(): while True: # 获取当前时间 current_time = int(time.time()) # 扫描DelayBucket,将延迟时间到达的Job放入ReadyQueue r.zrangebyscore('DelayBucket', 0, current_time, start=0, num=10).pipe( lambda x: x if x else None, lambda x: r.lpush('ReadyQueue', *x), lambda x: r.zremrangebyscore('DelayBucket', 0, current_time) ).execute() # 休眠1秒 time.sleep(1) # 从ReadyQueue中取出Job并执行 def process_ready_queue(): while True: # 从ReadyQueue中取出Job的ID job_id = r.brpop('ReadyQueue')[1] # 根据Job的ID从JobPool中获取Job的详细信息 job_info = r.hget('JobPool', job_id) # 执行相应的操作 print(f"Executing Job: {job_id}, Info: {job_info}") # 启动Timer和处理ReadyQueue的线程 timer_thread = threading.Thread(target=timer_scan) process_thread = threading.Thread(target=process_ready_queue) timer_thread.start() process_thread.start() ``` 请注意,上述代码只是一个简单的示例,实际的实现可能需要根据具体需求进行调整和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值