#### 1. TP6.0 消息队列 topthink/think-queue --- `topthink/think-queue` 是ThinkPHP官方提供的一个消息队列服务,是专门支持队列服务的扩展包 github : [https://github.com/top-think/think-queue](https://github.com/top-think/think-queue) packagist : [https://packagist.org/packages/topthink/think-queue](https://packagist.org/packages/topthink/think-queue) #### 2. think-queue 各主版本对应适用的TP版本 --- | think-queue 版本号 | 适用的TP版本 | | ------------ | ------------ | | 1.x | ThinkPHP5.0 | | 2.x | ThinkPHP5.1 | | 3.x | ThinkPHP6.0 | #### 3. 安装 topthink/think-queue --- 在应用根目录执行命令, 下载 `topthink/think-queue` 扩展 安装扩展后会自动生成消息队列配置文件 `config/queue.php` ``` composer require topthink/think-queue ``` #### 4. topthink/think-queue 驱动类型 --- | 驱动类型 | 对应的类型值 | | ------------ | ------------ | | sync | 同步执行, 默认值 | | database | 数据库驱动 | | redis | Redis驱动 【推荐】 | | 其他自定义的完整的类名 | ... | 如果驱动类型为 `sync`, 则以下两种发布任务的方式都会同步执行 当驱动类型修改为 `redis` 时, `think\facade\Queue::later()` 才会异步执行 ``` // 立即执行 think\facade\Queue::push($job, $data = '', $queue = null); // 延迟执行 think\facade\Queue::later($delay, $job, $data = '', $queue = null); ``` ``` return [ 'default' => 'sync', 'connections' => [ 'sync' => [ 'type' => 'sync', ], ... ], 'failed' => [ 'type' => 'none', 'table' => 'failed_jobs', ], ]; ``` #### 5. 发布任务 --- ``` // 立即执行 think\facade\Queue::push($job, $data = '', $queue = null); // 延迟执行 // $delay 延迟时间,单位秒,几秒后执行 // $job 任务对象 // $data 自定义数据 // $queue 队列名称 think\facade\Queue::later($delay, $job, $data = '', $queue = null); ``` ``` /** * 获取任务对象 * 发布任务时使用 * @param string $class * @param string $action * @example getJob(\app\queue\Task::class, 'fire') * @return string app\queue\task@fire */ function getJob(string $class, string $action) { // 使用示例 // $delay = 10; // $job = getJob(\app\queue\Task::class, 'fire'); // \think\facade\Queue::later($delay, $job, $data); return implode('@', [strtolower($class), $action]); } ``` #### 6. 监听任务并执行 --- 两种命令 ``` php think queue:work php think queue:listen ``` 两种命令的具体的可选参数可以输入命令加 --help 查看 ``` php think queue:work --help php think queue:listen --help ``` 常用参数 ``` // 任务执行五次还未成功, 第六次进入failed方法 php think queue:listen --tries 5 ```