easyswoole - 延迟队列
1.注册进程
在EasySwooleEvent.php中的initialize注册自定义进程
//延迟队列消费进程
$processConfig = new \EasySwoole\Component\Process\Config();
$processConfig->setProcessName('delayProcess');
\EasySwoole\Component\Process\Manager::getInstance()->addProcess(new Consumer($processConfig));
2.进程管理文件
在APP下创建文件夹Process并创建文件Consumer.php
<?php
namespace App\Process;
use EasySwoole\Component\Process\AbstractProcess;
use EasySwoole\Pool\Manager;
use Swoole\Coroutine;
use EasySwoole\RedisPool\RedisPool;
class Consumer extends AbstractProcess
{
protected function run($arg)
{
go(function () {
while (true) {
// 拿到redis
$redis = RedisPool::defer(); //自动回收
// 从有序集合中拿到三秒(模拟30分钟)以前的订单
$orderIds = $redis->zRangeByScore('delay_queue_test', 0, time() - 3, ['withscores' => TRUE]);
var_dump($orderIds);
if (empty($orderIds)) {
Coroutine::sleep(1);
continue;
}
//拿出后立马删除
$redis->zRem('delay_queue_test', ...$orderIds);
foreach ($orderIds as $orderId) {
var_dump($orderId);
//TODO:: 判断此订单30分钟后,是否仍未完成,做相应处理
}
}
});
}
}
3.控制器
控制器中应用延迟队列
function delayQueue()
{
$orderId = date('YmdHis', time());
$redis = RedisPool::defer(); //自动回收
$res = $redis->zAdd('delay_queue_test', time(), $orderId . '1', time(), $orderId . '2', time(), $orderId . '3');
if ($res) {
$this->writeJson(200, '订单添加成功:' . $orderId);
}
}