slaszu / redismq
使用php和Redis实现'可靠队列'模式
1.1.1
2016-06-22 11:43 UTC
Requires
- php: >=5.4
Requires (Dev)
- phpunit/phpunit: ^4.0
- predis/predis: ^1.0
This package is not auto-updated.
Last update: 2024-09-14 19:25:38 UTC
README
该想法来自Redis 文档
使用composer安装
composer require slaszu/redismq
重要
所有示例均可在tests/UsecaseTest.php中找到
配置
此库使用Predis连接到Redis服务器。因此,以下示例中需要predis对象
$this->client = new \Predis\Client([
'scheme' => 'tcp',
'host' => REDIS_SERVER_HOST,
'port' => REDIS_SERVER_PORT,
]);
创建队列
$queue = new \RedisMq\Queue($this->client, $name);
将任务(消息)添加到队列
// eg. this is message with array, but message could be a simple string either
$message = new \RedisMq\Message([
'x' => 2,
'string' => 'Message number 2',
'rand' => rand(10000, 99999)
]);
$queue->addMessage($message);
操作任务
获取待处理任务列表
$taskQty = 100;
$taskList = $queue->getTaskList($taskQty);
获取任务详情
$task = $taskList->getTask();
$message = $task->getMessage();
$body = $messageArray->getBody();
//variable $body is an array given in section "Add task (message) to queue"
确认任务
$task = $taskList->getTask();
/*
* .....
* proccess message (task details) from task and if is all right then confirm this task
* .....
*/
$task->confirm();
任务在确认后从队列中移除。
修复队列
当你从队列中获取TaskList时,任务将从队列移动到TaskList。TaskList中的任务不再存在于队列中。
在某些情况下,你可能希望将任务从TaskList移回队列。为此,请使用repairTaskLists方法。此方法接受一个参数(以秒为单位)。这是自TaskList创建以来经过的最短时间。此方法检查从队列创建的所有TaskList。
重要:如果TaskList中的所有任务都已确认,则该TaskList为空,Redis会立即删除该任务。
$queue = new \RedisMq\Queue($this->client, $name);
$queue->repairTaskLists(60); // 60 is time in seconds