开始就是老生常谈的话了,composer安装queue
composer require topthink/think-queue
安装完成后在vendor/topthink/think-queue/src目录下有个config.php 把它复制到根目录config目录下,改名为queue.php,有三种模式,同步模式/database(数据库)/Redis 三种,推荐使用Redis,下面贴一下配置文件代码
return [ 'default' => 'database', 'connections' => [ 'sync' => [ 'type' => 'sync', ], 'database' => [ 'type' => 'database', 'queue' => 'default', 'table' => 'jobs', ], 'redis' => [ 'type' => 'redis', 'queue' => 'default', 'host' => '127.0.0.1', 'port' => 6379, 'password' => '', 'select' => 0, 'timeout' => 0, 'persistent' => false, ], ], 'failed' => [ 'type' => 'none', 'table' => 'failed_jobs', ], ];
我用的是数据库,所以default是database,下面放数据表,字段可能有多余,凑合用吧。
CREATE TABLE `tp_account` ( `id` bigint(19) NOT NULL, `code` varchar(255) DEFAULT NULL, `loginID` varchar(255) DEFAULT NULL, `remark` varchar(255) DEFAULT NULL, `status` tinyint(1) DEFAULT NULL, `online` tinyint(1) DEFAULT NULL, `cookies` varchar(2500) DEFAULT NULL, `openid` varchar(255) DEFAULT NULL, `errMsg` varchar(255) DEFAULT NULL, `zoneid` varchar(60) DEFAULT NULL, `max_amount` int(11) DEFAULT NULL, `day_amount` int(11) DEFAULT NULL, `time` int(11) DEFAULT NULL, `day_time` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
下面放需要使用消息队列的场景,我这里的场景是生成支付订单后没有回调接口获取订单完成情况,只能自己去发起请求去查询订单完成与否,所以在生成订单之后就会投放一个查询到队列中。
需要调用消息队列的页面。
<?php namespace appindexcontroller; use thinkfacadeQueue; class Index { public function pay() { $jobQueueName = 'checkOrder'; $orderData = ['oid'=>123]; //假设订单id是123 $isPushed = Queue::later(3,Job1::class,$orderData,$jobQueueName); } }
消息队列页面
<?php namespace appjob; use thinkqueueJob; class Job1{ public function fire(Job $job, $data){ if($this->queryOrder($data['oid]){ //修改订单状态完成 $job->delete(); return true; }else if($job->attempts() >60){ //查询60次后依然没有结果,删除队列,停止查询,该订单判定为未支付。 $job->delete(); return false; }else{ $job->release(2); //如果查询不到60次,并且还未支付成功,就延时两秒重新投放到队列中查询。 return true } } public function queryOrder($id){ //这里写查询订单的逻辑,查询订单是否已支付 return true; } public function failed($data){ // ...任务达到最大重试次数后,失败了 } }
ok,写完了,最后在tp6 根目录下运行php think queue:work --queue checkOrder,就能让这条消息队列执行起来了, --queue后面的名称是一开始传到消息队列的队列名。