安装:composer require topthink/think-queue:3.0.7.
配置:app\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' => env('redis.host', '127.0.0.1'),
'port' => env('redis.port', 6379),
'password' => env('redis.password', ''),
'select' => 0,
'timeout' => 0,
'persistent' => false,
],
],
'failed' => [
'type' => 'none',
'table' => 'failed_jobs',
],
];
创建文件如图:
TestJobController.php
创建消费者
<?php
namespace app\api\controller;
use think\facade\Log;
use think\queue\Job;
class TestJobController
{
/**
* fire方法是消息队列默认调用的方法
* @param Job $job 当前的任务对象
* @param array $data 发布任务时自定义的数据
*/
public function fire(Job $job, array $data)
{
// 有些任务在到达消费者时,可能已经不再需要执行了
$isJobStillNeedToBeDone = $this->checkDatabaseToSeeIfJobNeedToBeDone($data);
if (!$isJobStillNeedToBeDone) {
$job->delete();
return;
}
$isJobDone = $this->doHelloJob($data);
if ($isJobDone){
$job->delete();
echo "删除任务" . $job->attempts() . '\n';
}else{
if ($job->attempts() > 3){
$job->delete();
echo "超时任务删除" . $job->attempts() . '\n';
}
}
}
/**
* 有些消息在到达消费者时,可能已经不再需要执行了
* @param array $data
* @return bool
*/
private function checkDatabaseToSeeIfJobNeedToBeDone(array $data)
{
return true;
}
/**
* 根据消息中的数据进行实际的业务处理...
* @param array $data
* @return bool
*/
private function doHelloJob(array $data)
{
Log::info('*999999999999999999999999');
Log::info($data);
return true;
}
}
创建生产者、
<?php
namespace app\api\controller;
use think\facade\Log;
use app\api\logic\UserLogic;
use app\api\validate\PasswordValidate;
use app\api\validate\SetUserInfoValidate;
use app\api\validate\UserValidate;
use think\facade\Queue;
use app\api\service\Aes;
/**
* 用户控制器
* Class UserController
* @package app\api\controller
*/
class UserController extends BaseApiController
{
public array $notNeedLogin = ['resetPassword','buildSign','verifySign'];
public function buildSign()
{
// 当轮到该任务时,系统将生成该类的实例,并调用其fire方法
$jobHandlerClassName = 'app\api\controller\TestJobController';
// 2.当任务归属的队列名称,如果为新队列,会自动创建
$jobQueueName = "helloJobQueue";
// 3.当前任务所需业务数据,不能为resource类型,其他类型最终将转化为json形式的字符串
$jobData = ['ts' => time(), 'bizId' => uniqid(), 'a' => 1];
// 4.将该任务推送到消息列表,等待对应的消费者去执行
// 入队列,later延迟执行,单位秒,push立即执行
$isPushed = Queue::later(5, $jobHandlerClassName, $jobData, $jobQueueName);
// database 驱动时,返回值为 1|false ; redis 驱动时,返回值为 随机字符串|false
if ($isPushed !== false) {
return $this->success('推送成功',[]);
} else {
return $this->fail('推送失败');
}
}
}
当我们开启了work进程时
php think queue:work --queue helloJobQueue