Laravel队列任务完成后通过Pusher发送$ids变量的实现方法(Queue::after用法解惑)
解决Laravel队列任务完成后通过Pusher发送$ids的问题
我明白你已经卡了3天,别着急,我们一步步来实现这个功能。核心就是利用Queue::after回调捕获任务完成事件,再结合Pusher推送数据,具体操作如下:
步骤1:修改队列任务类,暴露$ids变量
你当前的$ids是handle()方法里的局部变量,外部回调无法获取。我们需要把它改成任务类的公共属性:
class ShipWithAramex implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $data; public $type; public $auth_id; public $validatedOrders; // 新增公共属性存储ids public $ids = []; public function __construct($data,$type,$validatedOrders,$auth_id) { $this->data=$data; $this->type=$type; $this->auth_id=$auth_id; $this->validatedOrders=$validatedOrders; } public function handle() { try { // 移除原来的局部$ids声明,直接使用类属性 $armx = new Aramex(); foreach ($this->data as $key => $order) { // 直接往类属性里push订单ID array_push($this->ids,$order->id); // ... 剩下的业务逻辑代码保持不变 } } catch (\Throwable $th) { $this->failed($th); } } // ... 其他方法保持不变 }
步骤2:注册Queue::after回调
我们需要在Laravel的服务提供者里注册队列完成后的回调,最常用的是App\Providers\AppServiceProvider的boot()方法:
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Queue; use Illuminate\Queue\Events\JobProcessed; use App\Jobs\ShipWithAramex; use Illuminate\Support\Facades\Log; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { // 注册队列任务完成后的回调 Queue::after(function (JobProcessed $event) { // 只处理我们关心的ShipWithAramex任务 if ($event->job->payload()['displayName'] === ShipWithAramex::class) { // 获取任务实例 /** @var ShipWithAramex $jobInstance */ $jobInstance = app($event->job->resolveName()); // 从任务实例中取出ids $ids = $jobInstance->ids; // 调用Pusher发送数据 $pusher = app('pusher'); try { // 替换成你的Pusher频道名和事件名(可自定义) $pusher->trigger( 'orders-shipped-channel', 'orders-completed', ['ids' => $ids] ); Log::info('Pusher推送成功,订单ID列表:'.implode(',', $ids)); } catch (\Exception $e) { Log::error('Pusher推送失败:'.$e->getMessage()); } } }); } /** * Register any application services. * * @return void */ public function register() { // } }
步骤3:验证Pusher基础配置
确保你的.env文件里已经正确配置了Pusher的核心信息:
PUSHER_APP_ID=你的应用ID PUSHER_APP_KEY=你的应用KEY PUSHER_APP_SECRET=你的应用SECRET PUSHER_APP_CLUSTER=你的集群(比如mt1)
额外提示
- 如果需要监听任务失败的情况,可以在
failed()方法里也添加Pusher推送逻辑,方便前端感知异常。 - 测试时可以用
php artisan queue:work --tries=1启动队列,确保任务执行完成后能触发回调。 - 因为任务默认使用
SerializesModels,$ids是数组类型,完全支持序列化,不用担心数据丢失问题。
这样配置完成后,每当ShipWithAramex任务执行完成,就会自动通过Pusher把$ids推送到你指定的频道和事件里,前端只需要监听对应的频道事件就能收到数据了!
内容的提问来源于stack exchange,提问作者bekico1681
相关产品推荐
相关产品推荐

