前提
首先需要安装redis,因为本文章使用了redis驱动。
安装
首先查看ThinkPHP框架版本,然后进入Packagist官网搜索think-queue
,并根据ThinkPHP版本选择对应think-queue
版本。
thinkphp-queue
地址:https://packagist.org/packages/topthink/think-queue
本文采用的ThinkPHP的版本为5.1
,查询选择think-queue
的版本为2.0.*
。
在项目根目录下的conposer.json中添加think_queue的信息
"require": {
"php": ">=5.6.0",
"topthink/framework": "5.1.*",
"topthink/think-captcha": "2.0.*",
"topthink/think-image": "^1.0",
"topthink/think-helper": "1.0.*",
"topthink/think-migration": "2.0.*",
"topthink/think-worker": "2.0.*",
"topthink/think-mongo": "2.0.*",
"topthink/think-testing": "2.0.*",
"topthink/think-queue": "2.0.*"
},
添加完成后使用composer update
更新composer.json
中配置项的版本。
think_queue安装完成之后会在config目录下生成queue.php文件,修改为图片内容,使用redis驱动
<?php
return [
'connector' => 'Redis', // Redis 驱动
'expire' => 60, // 任务的过期时间,默认为60秒; 若要禁用,则设置为 null
'default' => 'default', // 默认的队列名称
'host' => '127.0.0.1', // redis 主机ip
'port' => 6379, // redis 端口
'password' => '', // redis 密码
'select' => 0, // 使用哪一个 db,默认为 db0
'timeout' => 0, // redis连接的超时时间
'persistent' => false, // 是否是长连接
];
在application下创建job目录,然后在job目录中创建文件CloseOrder.php文件
<?php
namespace app\job;
use think\queue\Job;
use think\Db;
class CloseOrder {
public function fire(Job $job, $data){
//判断是否是未支付的订单,否则返回(根据实际情况调整)
if ($data['status'] != 2) {
$job->delete();
return;
}
// 更新订单状态为已取消 (根据实际调整)
$one['status'] = 0;
$result = Db::name('order')->where('id',1)->update($one);
if($result!==false){
// 如果执行成功则删除任务
$job->delete();
}else{
// 重复3次都没结束则强制删除任务
if ($job->attempts() > 3) {
$job->delete();
return;
}else{
// 延迟10秒钟再执行一次这个任务
$job->release(10);
}
}
}
public function failed($data){
// ...任务达到最大重试次数后,失败了
}
}
?>
在提交完订单控制器方法中添加 30代表30秒
<?php
namespace app\index\controller;
use app\job\CloseOrder; //引入
use think\Db;
use think\Controller;
use think\Queue;
class One extends Controller
{
public function index(){
$order = Db::name('order')->where('id',1)->find();
Queue::later(30, CloseOrder::class,$order, $queue = null); //此方法
}
}
本地测试需要在项目下执行cmd,然后进程一直存在才可以成功,
监听任务并执行:
php think queue:listen
php think queue:work