当前位置:   article > 正文

TP5.1/Thinkcmf5.1使用think-queue实现异步延迟队列_thinkcmf5 queue

thinkcmf5 queue

这边尤其要注意插件的版本和thinkphp的版本相对应,否则会碰到不少问题,我会把我走的弯路也一并分享一下。

前置工作:安装TP5.1/Thinkcmf5.1、安装Redis及PHP的redis扩展

一、首先安装think-queue插件

网上很多文章直接写 composer require topthink/think-queue 的,会发现安装完出现各种问题,因为这样是直接现在插件最新版本,而目前think-queue已经v3+的版本了,3.*的版本是适用于tp6的

  1. # Thinkphp5.1
  2. composer require topthink/think-queue:2.*
  3. # Thinkphp6
  4. composer require topthink/think-queue:3.*

我装的是2.0.4版本

composer require topthink/think-queue 2.0.4

安装完成之后会生成一个config/queue.php文件,但我这里因为是用的thinkcmf5.1的框架,所以我这边做了两处修改,如果是tp5.1的可跳过下面步骤直接看第二步

1、删除config文件夹

2、在data/config/app.php中添加queue配置

  1. 'queue'=>[
  2. 'connector' => 'Redis',
  3. 'expire' => 60, // 任务的过期时间,默认为60秒; 若要禁用,则设置为 null
  4. 'default' => 'sync_queue', // 默认的队列名称
  5. 'host' => '127.0.0.1', // redis 主机ip
  6. 'port' => 6379, // redis 端口
  7. 'password' => '', // redis 密码
  8. 'select' => 4, // 使用哪一个 db,默认为 db0
  9. 'timeout' => 0, // redis连接的超时时间
  10. 'persistent' => false, // 是否是长连接
  11. ]

如下图

​​​​​​​

 3、修改vendor/topthink/think-queue/src/Queue.php文件的第33行

二、消息的创建与推送

我们在控制器中执行测试代码,将数据推送到helloJobQueue队列

  1. <?php
  2. /**
  3. * 测试代码
  4. */
  5. namespace api\wxapp\controller;
  6. use think\Controller;
  7. use think\Queue;
  8. class IndexController extends Controller
  9. {
  10. public function test(){
  11. //任务执行类(消费者消费的处理逻辑)
  12. $jobHandlerClassName = "app\job\Test@fire";
  13. //队列名,如不存在会自动创建
  14. $jobQueueName = "helloJobQueue";
  15. //推送的业务数据
  16. $jobData = [ 'name' => 'test'.rand(), 'password'=>rand()];
  17. //延迟推送,推送后等待消费者消费
  18. // $isPushed = Queue::later(300, $jobHandlerClassName , $jobData , $jobQueueName );
  19. //立即推送,等待消费者消费
  20. $isPushed = Queue::push($jobHandlerClassName , $jobData , $jobQueueName );
  21. // database 驱动时,返回值为 1|false ; redis 驱动时,返回值为 随机字符串|false
  22. if( $isPushed !== false ){
  23. echo date('Y-m-d H:i:s') . " a new Hello Job is Pushed to the MQ"."<br>";
  24. }else{
  25. echo 'Oops, something went wrong.';
  26. }
  27. }
  28. }

当写完这一步时,访问接口路径就可以发布任务了;在浏览器中访问 http://your.project.domain/api/wxapp/index/test ,可以看到消息推送成功:2022-02-23 16:51:56 a new Hello Job is Pushed to the MQ

消息推送成功后可以用redis可视化工具查看redis数据进行验证

 三、消息的消费与删除

新建可执行类,创建的路径要与上面创建任务代码中任务执行类的$jobHandlerClassName路径一致。

  1. <?php
  2. /**
  3. * 文件路径: \application\index\job\Hello.php
  4. * 这是一个消费者类,用于处理 helloJobQueue 队列中的任务
  5. */
  6. namespace app\job;
  7. use think\queue\Job;
  8. class Test {
  9. /**
  10. * fire方法是消息队列默认调用的方法
  11. * @param Job $job 当前的任务对象
  12. * @param array|mixed $data 发布任务时自定义的数据
  13. */
  14. public function fire(Job $job,$data){
  15. // 如有必要,可以根据业务需求和数据库中的最新数据,判断该任务是否仍有必要执行.
  16. $isJobStillNeedToBeDone = $this->checkDatabaseToSeeIfJobNeedToBeDone($data);
  17. if(!$isJobStillNeedToBeDone){
  18. $job->delete();
  19. return;
  20. }
  21. $isJobDone = $this->doHelloJob($data);
  22. if ($isJobDone) {
  23. //如果任务执行成功, 记得删除任务
  24. $job->delete();
  25. }else{
  26. if ($job->attempts() > 3) {
  27. //通过这个方法可以检查这个任务已经重试了几次了
  28. $job->delete();
  29. // 也可以重新发布这个任务
  30. //$job->release(2); //$delay为延迟时间,表示该任务延迟2秒后再执行
  31. }
  32. }
  33. }
  34. /**
  35. * 有些消息在到达消费者时,可能已经不再需要执行了
  36. * @param array|mixed $data 发布任务时自定义的数据
  37. * @return boolean 任务执行的结果
  38. */
  39. private function checkDatabaseToSeeIfJobNeedToBeDone($data){
  40. return true;
  41. }
  42. /**
  43. * 根据消息中的数据进行实际的业务处理
  44. * @param array|mixed $data 发布任务时自定义的数据
  45. * @return boolean 任务执行的结果
  46. */
  47. private function doHelloJob($data) {
  48. // 根据消息中的数据进行实际的业务处理...
  49. // test
  50. if (!empty($data)) {
  51. \api\common\lib\dingtalk\Robot::getInstance()->setContent("消息推送:" . json_encode($data))->send("xxxx");
  52. }
  53. return true;
  54. }
  55. }

我这边在doHelloJob方法中处理了一下数据的钉钉消息推送来测试

执行任务需要使用php命令行方式去执行

  1. #命令:php think queue:work --queue 队列名
  2. 例:php think queue:work --queue helloJobQueue

坑1:我之前装的think-queue版本是1.1.4的时候,在这一步运行时报错

  1. [think\exception\ThrowableError]
  2. Fatal error: Using $this when not in object context
  3. Exception trace:
  4. () at /www/wwwroot/test/vendor/thinkphp/library/think/Hook.php:146
  5. think\Hook::listen() at /www/wwwroot/test/vendor/topthink/think-queue/src/queue/Worker.php:35
  6. think\queue\Worker->pop() at /www/wwwroot/test/vendor/topthink/think-queue/src/queue/command/Work.php:75
  7. think\queue\command\Work->execute() at /www/wwwroot/test/vendor/thinkphp/library/think/console/Command.php:175
  8. think\console\Command->run() at /www/wwwroot/test/vendor/thinkphp/library/think/Console.php:675
  9. think\Console->doRunCommand() at /www/wwwroot/test/vendor/thinkphp/library/think/Console.php:261
  10. think\Console->doRun() at /www/wwwroot/test/vendor/thinkphp/library/think/Console.php:198
  11. think\Console->run() at /www/wwwroot/test/vendor/thinkphp/library/think/Console.php:115
  12. think\Console::init() at /www/wwwroot/test/think:33

正确的执行应该是:

至此,我们成功地经历了一个消息的 创建 -> 推送 -> 消费 -> 删除 的基本流程

参考文章: thinkphp-queue自带的队列包使用分析_will5451的博客-CSDN博客_php queue

四、守护进程,保证进程常驻

很多自己使用PHP+Redis的list类型实现的简单队列是将数据存在redis中,然后通过定时脚本轮询的去执行命令去触发消费,但对于脚本的运行没有做到一个守护

supervisor是用Python开发的一个client/server服务,是Linux/Unix系统下的一个进程管理工具。可以很方便的监听、启动、停止、重启一个或多个进程。用supervisor管理的进程,当一个进程意外被杀死,supervisor监听到进程死后,会自动将它重启,很方便的做到进程自动恢复的功能,不再需要自己写shell脚本来控制

下面来说一下supervisor的安装和配置

  1. # 安装supervisor
  2. yum install supervisor
  3. # 设置开机自启
  4. systemctl enable supervisord.service
  5. # 进入配置文件目录
  6. cd /etc/supervisord.d
  7. # 创建配置文件 一个进程一个配置文件 名字自己随意
  8. vim process.ini
  9. # 配置文件内容
  10. [program:自定义名称]
  11. process_name=进程名称
  12. command=php /www/wwwroot/项目目录/think queue:work --queue 需监听的队列名称
  13. directory= /www/wwwroot/项目目录
  14. autostart=true
  15. autorestart=true
  16. user=www #如有权限问题可修改为root
  17. numprocs=1
  18. redirect_stderr=true
  19. stdout_logfile=/root/日志文件名称.log
  20. # 保存后执行已下命令
  21. supervisorctl reread
  22. supervisorctl update

坑2:当我安装完并且修改完配置后,执行supervisorctl reread的时候报错

error: <class 'socket.error'>, [Errno 2] No such file or directory: file: /usr/lib64/python2.7/socket.py line: 224

网上找到一个处理方法,使用以下命令来重启服务:

/usr/bin/python2 /usr/bin/supervisord -c /etc/supervisor/supervisord.conf

 supervisor常用命令

  1. # 启动
  2. systemctl start supervisord.service
  3. # 停止
  4. systemctl stop supervisord.service
  5. # 重启
  6. systemctl restart supervisord.service
  7. # 查看进程状态
  8. supervisorctl status
  9. # 关闭进程 stop后边可增加进程名称参数 all为关闭所有
  10. supervisorctl stop all
  11. # 启动进程 同上
  12. supervisorctl start all
  13. # 重启进程 同上
  14. supervisorctl restart all
  15. # 重新读取配置文件
  16. supervisorctl reread
  17. # 更新配置到进程
  18. supervisorctl update
  19. # 重新启动配置中的所有程序
  20. supervisorctl reload
  21. # 启动某个进程(program_name=你配置中写的程序名称)
  22. supervisorctl start program_name
  23. # 停止某一进程 (program_name=你配置中写的程序名称)
  24. pervisorctl stop program_name
  25. # 重启某一进程 (program_name=你配置中写的程序名称)
  26. supervisorctl restart program_name

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/285071
推荐阅读
  

闽ICP备14008679号