12
03月
2020
首先在你的服务器或者本地搭一套tp5程序
然后添加think-queue 扩展
很简单 进入到tp5目录
执行composer require topthink/think-queue
可能会遇到这个问题
用php-v 查看你的php版本
去找到对应的php.ini 搜索disable_functions 把后面的putenv移出
然后继续执行composer require topthink/think-queue
由于版本问题,系统会默认下载最新版本
所以需要更改think-queue 版本 https://github.com/coolseven/notes/tree/master/thinkphp-queue
可去官方或者查询资料查找对应版本 通过修改composer.json
执行composer update下载对应版本
下载完之后会在application/extra中出现queue.php文件
选择你要的驱动 这里我选redis
在服务器安装Redis 缓存
配置好redis以后
可以开始写测试代码了
首先在index下面创建一个测试控制器
<?php namespace app\index\controller; use think\Exception; use think\Queue; class JobTest { public function actionWithHelloJob(){ //选择执行类 $jobHandlerClassName = 'app\index\job\Hello'; // 2. 当前任务归属的队列名称,如果为新队列,会自动创建 $jobQueueName = "helloJobQueue"; // 3.当前任务所需的业务数据 . 不能为 resource 类型,其他类型最终将转化为json形式的字符串 // ( jobData 为对象时,存储其public属性的键值对 ) $jobData = [ 'ts' => time(), 'bizId' => uniqid() ,'a' => 1 ] ; // 4. 将该任务推送到消息队列,等待对应的消费者去执行 $isPushed = Queue::push( $jobHandlerClassName , $jobData , $jobQueueName ); // database 驱动时,返回值为 1|false ; redis 驱动时,返回值为 随机字符串 |false if( $isPushed !== false ){ echo date('Y-m-d H:i:s') . " a new Hello Job is Pushed to the MQ"."<br>"; }else{ echo 'Oops, something went wrong.'; } } }
然后创建消费类
这里我和官方文档保持一致
执行对应控制器方法往队列中添加消息
然后在xshell里面执行php think queue:work --queue helloJobQueue
queue 有work 和listen 区别 注意使用场景
可在宝塔后台使用工具对进程开启守护
执行效果