laravel 事件+队列 使用案例讲解分析
场景:出发事件,在监听事件的监听器内引入队列机制,异步处理监听事件对应的业务
- 定义事件:目录app/Events(路径没有就手动建)下 新建文件DeomEvent.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class DeomEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* @var int
*/
public $exam_id = 0;
/**
* @var array
*/
public $departments = [];
public $areaIdList = [];
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(array $args)
{
$this->参数1 = $args['参数1键值'] ?? 0;
$this->参数2 = $args['参数2键值'] ?? 0;
}
}
- 定义监听器 目录 app/Listeners 下新建 demoEventListerSubscriber.php
<?php
namespace App\Listeners;
use App\Events\DeomEvent;
use Illuminate\Support\Facades\Log;
use Illuminate\Contracts\Queue\ShouldQueue;
class demoEventListerSubscriber implements ShouldQueue
{
public $delay = 10;//延迟10s执行任务
public function subscribe()
{
return [
DeomEvent::class => [
[self::class, 'handDemo1']
]
];
}
public function handDemo1(ExamsDepEvent $event)
{
//自己的业务数据 参数 $event->参数1
}
}
3.确保自己laravel 配置上了消息队列,不会的看我文章:https://blog.csdn.net/m0_37678007/article/details/119378312
4.启动消息队列处理事件触发的任务
php artisan queue:work