消息队列整个流程分为生产和消费,生产有由程序发起。消费由命令执行。
消息队列文件一般存放在app/jobs目录下。可以以一个类为一个队列进行开发,或者一个类中有多个小队列都能加入生产进行消费。目前推荐一个类为一个队列进行开发。
例如:新增记录管理员操作日志队列
创建文件 app\jobs\AdminLogJob.php
handle方法中一定要返回执行的结果,例如返回true,证明当前逻辑执行完成,没有任何问题不需要二次执行.会立即销毁当前队列;
如果因某个逻辑执行错误返回false或者0或者null或者空字符串都认定本次执行的任务失败,需要再次加入队列继续执行一次,直到执行返回成功为止。或者执行3次后也会自动销毁当前队列。
namespace app\jobs;use app\services\system\log\SystemLogServices;use crmeb\basic\BaseJobs;use crmeb\traits\QueueTrait;/*** 后台日志* Class AdminLogJob* @package app\jobs*/class AdminLogJob extends BaseJobs{use QueueTrait;public function handle($adminId, $adminName, $module, $rule, $ip, $type){//写入数据库逻辑//必须返回执行最后的结果return true;}public function test(){//测试小队列执行return true;}}
use app\jobs\AdminLogJob;//加入队列默认会直接执行handle内的逻辑AdminLogJob::dispatch([$adminId, $adminName, $module, $rule, $ip, $type]);//加入延迟队列,延迟600秒后执行,默认执行handle内的逻辑AdminLogJob::dispatchSece(600, [$adminId, $adminName, $module, $rule, $ip, $type]);//加入队列,执行AdminLogJob内的test方法AdminLogJob::dispatch('test', [$adminId, $adminName, $module, $rule, $ip, $type]);//加入延迟队列,延迟600秒后执行,执行AdminLogJob内的test方法//建议一个队列处理一个逻辑,当前示范的是多个小队列AdminLogJob::dispatchSece(600,'test', [$adminId, $adminName, $module, $rule, $ip, $type], 600);
以下为调试队列的写法,不能使用在正常流程中,只为了调试使用。
use app\jobs\AdminLogJob;//直接实例化调试当前job时候执行成功$res = (new AdminLogJob)->handle($adminId, $adminName, $module, $rule, $ip, $type);var_dump($res);
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号