本文實(shí)例講述了php使用redis的有序集合zset實(shí)現(xiàn)延遲隊(duì)列。分享給大家供大家參考,具體如下:
延遲隊(duì)列就是個(gè)帶延遲功能的消息隊(duì)列,相對(duì)于普通隊(duì)列,它可以在指定時(shí)間消費(fèi)掉消息。
延遲隊(duì)列的應(yīng)用場(chǎng)景:
1、新用戶注冊(cè),10分鐘后發(fā)送郵件或站內(nèi)信。
2、用戶下單后,30分鐘未支付,訂單自動(dòng)作廢。
我們通過redis的有序集合zset來實(shí)現(xiàn)簡單的延遲隊(duì)列,將消息數(shù)據(jù)序列化,作為zset的value,把消息處理時(shí)間作為score,每次通過zRangeByScore獲取一條消息進(jìn)行處理。
?php
class DelayQueue
{
protected $prefix = 'delay_queue:';
protected $redis = null;
protected $key = '';
public function __construct($queue, $config = [])
{
$this->key = $this->prefix . $queue;
$this->redis = new Redis();
$this->redis->connect($config['host'], $config['port'], $config['timeout']);
$this->redis->auth($config['auth']);
}
public function delTask($value)
{
return $this->redis->zRem($this->key, $value);
}
public function getTask()
{
//獲取任務(wù),以0和當(dāng)前時(shí)間為區(qū)間,返回一條記錄
return $this->redis->zRangeByScore($this->key, 0, time(), ['limit' => [0, 1]]);
}
public function addTask($name, $time, $data)
{
//添加任務(wù),以時(shí)間作為score,對(duì)任務(wù)隊(duì)列按時(shí)間從小到大排序
return $this->redis->zAdd(
$this->key,
$time,
json_encode([
'task_name' => $name,
'task_time' => $time,
'task_params' => $data,
], JSON_UNESCAPED_UNICODE)
);
}
public function run()
{
//每次只取一條任務(wù)
$task = $this->getTask();
if (empty($task)) {
return false;
}
$task = $task[0];
//有并發(fā)的可能,這里通過zrem返回值判斷誰搶到該任務(wù)
if ($this->delTask($task)) {
$task = json_decode($task, true);
//處理任務(wù)
echo '任務(wù):' . $task['task_name'] . ' 運(yùn)行時(shí)間:' . date('Y-m-d H:i:s') . PHP_EOL;
return true;
}
return false;
}
}
$dq = new DelayQueue('close_order', [
'host' => '127.0.0.1',
'port' => 6379,
'auth' => '',
'timeout' => 60,
]);
$dq->addTask('close_order_111', time() + 30, ['order_id' => '111']);
$dq->addTask('close_order_222', time() + 60, ['order_id' => '222']);
$dq->addTask('close_order_333', time() + 90, ['order_id' => '333']);
然后,我們寫一個(gè)php腳本,用來處理隊(duì)列中的任務(wù)。
?php
set_time_limit(0);
$dq = new DelayQueue('close_order', [
'host' => '127.0.0.1',
'port' => 6379,
'auth' => '',
'timeout' => 60,
]);
while (true) {
$dq->run();
usleep(100000);
}
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php+redis數(shù)據(jù)庫程序設(shè)計(jì)技巧總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《PHP基本語法入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- 基于Redis延遲隊(duì)列的實(shí)現(xiàn)代碼
- SpringBoot集成Redisson實(shí)現(xiàn)延遲隊(duì)列的場(chǎng)景分析
- Redis延遲隊(duì)列和分布式延遲隊(duì)列的簡答實(shí)現(xiàn)