步骤:
驱动选择
在.env环境中修改QUEUE_DRIVER=database来实现
定义任务
分发任务
启动队列
系统通知队列的实现:
1、创建database的queue表:php artisan queue:table
2、创建任务:php artisan make:job SendMessage
在jobs文件夹下的SendMessage中编写
构造函数中注入要发送的通知,hander中编写通知要发送的用户。加入到用户与通知的关联表里面
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class SendMessage implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private $notice;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(\App\Http\Model\Notice $notice)
{
$this->notice = $notice;
//
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
//通知每个用户系统消息
$users = \App\User::all();
foreach($users as $user){
$user->addNotice($this->notice);
}
}
}
3、在后台中保存通知的方法前调用
$notice = Notice::create(request(['title','content']));
$this->dispatch(new \App\Jobs\SendMessage($notice));
4、启动队列
php artisan queue:work
开启常驻内存服务
若在Linux的常驻内存:
nohup php artisan queue:work >> /dev/null &
5、在前端视图中显示