PHP code example of shali / redis-delayedmq
1. Go to this page and download the library: Download shali/redis-delayedmq library. Choose the download type require. 2. Extract the ZIP file and open the index.php. 3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
shali / redis-delayedmq example snippets
$host = '127.0.0.1';
$port = 6379;
$db = 6;
$queue_name = 'close_order';
$redis = new \Redis();
$redis->connect($host, $port);
$redis->select($db);
# 客户端使用
$client = \Shali\RedisDelayedMQ\Client::make($redis);
$client->useQueue($queue_name);
$order = 'pay20210509050607';
// 生产者:支付订单10分钟未支付,则关闭
$client->put($order, 10 * 60);
// 消费者:获取待检查关闭的订单
if ($client->haveReadyJob()) {// 双重检查:1
// 获取延时到期的任务,默认获取的任务不指定 ttr
$task = $client->reserve();
if (null === $task) {// 双重检查:2
return;
}
// 处理任务...
if (true) {
// 消费者:任务处理成功,将其从队列移除
$client->delete($task);
} else {
// 任务处理不达预期,延时 10s 后再执行
$client->release($task, 10);
}
}
# 只有服务端运行起来,才支持超时重发
$server = new \Shali\RedisDelayedMQ\Server($redis);
while (true) {
// 将处理超时的任务,再次丢进去处理
$server->run();
}