先安装redis+php redis扩展
安装think-queue
composer require topthink/think-queue
修改配置
\config\queue.php
<?php
return [
'default' => 'redis',
'connections' => [
'sync' => [
'type' => 'sync',
],
'database' => [
'type' => 'database',
'queue' => 'default',
'table' => 'jobs',
'connection' => null,
],
'redis' => [
'type' => 'redis',
'queue' => 'default',
'host' => '127.0.0.1',
'port' => 6379,
'password' => '',//设置redis密码,如果没有密码为空
'select' => 0,
'timeout' => 0,
'persistent' => false,
],
],
'failed' => [
'type' => 'none',
'table' => 'failed_jobs',
],
];
消息队列DEMO
<?php
namespace app\api\controller;
use think\facade\Queue;
class Test
{
/**
* 多模块延迟队列实现
*/
public function test()
{
$orderData = [
"orderId" => uniqid()
];
$isPushed = Queue::later(5, "app\api\controller\Job1", json_encode($orderData), "test");
if ($isPushed) echo "\n 订单支付成功 \n";
die;
}
}
<?php
/**
* Created by PhpStorm.
* User: Pasa吴
* Date: 2022/5/23
* Time: 20:51
*/
namespace app\api\controller;
use think\queue\Job;
class Job1
{
public function fire(Job $job, $data)
{
$data = json_decode($data, true);
if ($this->doJob($data)) {
$job->delete();
} else {
if ($job->attempts() > 3) {
print_r("订单超时:" . $data['orderId']);
$job->delete();
}
}
}
public function doJob($data)
{
xdebug($data);
print_r("发送支付成功通知:" . $data['orderId']);
return true;
}
}
监听消息队列
php think queue:listen --queue test