1. 安装queue 组件
composer require topthink/think-queue
2 . 配置队列 queue.php
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <448901948@qq.com>
// +----------------------------------------------------------------------
return [
'default' => 'redis',
'connections' => [
'sync' => [
'type' => 'sync',
],
'database' => [
'type' => 'database',
'queue' => 'default',
'table' => 'jobs',
'connection' => null,
],
'redis' => [
'type' => 'redis',
'queue' => 'default',
'host' => env('redis.host', '127.0.0.1'),
'port' => env('redis.port', '6379'),
'password' => env('redis.password','0'),
'select' => 1,
'timeout' => 0,
'persistent' => true,
],
],
'failed' => [
'type' => 'none',
'table' => 'failed_jobs',
],
];
3. 创建生产者
<?php
/**
* 队列生产端
*/
namespace app\admin\controller;
use think\facade\Queue;
use think\Request;
class Job
{
public function job(Request $request){
$params = $request->get();
$jobHandlerClassName = 'app\job\Task';
$jobQueueName = 'task';
$orderData = ['order_sn'=>$params['id']];
//Queue::later();//立即执行
//$isPushed = Queue::later(5, $jobHandlerClassName, $orderData, $jobQueueName); //这儿的10是指10秒后执行队列任务
$isPushed = Queue::push( $jobHandlerClassName, $orderData, $jobQueueName); //这儿的10是指10秒后执行队列任务
if($isPushed !== false){
echo '队列添加成功';
}else{
echo '插入失败了';
}
}
}
4. 创建消费者
<?php
namespace app\job;
use think\queue\Job;
class Task
{
public function fire(Job $job, $data)
{
$rt = $this->doJob($data);
if($rt){
$job->delete();
return true;
}else{
echo '消费失败';
}
// 重试三次失败 todo...
if($job->attempts() == 3){
$job->delete();
return false;
}
//执行失败10S后重试
$job->release(10);
}
public function doJob($data)
{
echo date('Y-m-d H:i:s')."\n";
return false;
}
}
5. 运行命令行
注意: 必须要带任务名,我这边不带任务名,无法监听到消息
使用 listen 监听
php think queue:listen --queue 任务名称
使用work监听
php think queue:work --queue 任务名称
可配合supervisor使用,保证进程常驻