步驟:
驅(qū)動(dòng)選擇
在.env環(huán)境中修改QUEUE_DRIVER=database來實(shí)現(xiàn)
定義任務(wù)
分發(fā)任務(wù)
啟動(dòng)隊(duì)列
系統(tǒng)通知隊(duì)列的實(shí)現(xiàn):
1、創(chuàng)建database的queue表:php artisan queue:table
2、創(chuàng)建任務(wù):php artisan make:job SendMessage
在jobs文件夾下的SendMessage中編寫
構(gòu)造函數(shù)中注入要發(fā)送的通知,hander中編寫通知要發(fā)送的用戶。加入到用戶與通知的關(guān)聯(lián)表里面
<?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()
{
//通知每個(gè)用戶系統(tǒng)消息
$users = \App\User::all();
foreach($users as $user){
$user->addNotice($this->notice);
}
}
}
3、在后臺(tái)中保存通知的方法前調(diào)用
$notice = Notice::create(request(['title','content']));
$this->dispatch(new \App\Jobs\SendMessage($notice));
4、啟動(dòng)隊(duì)列
php artisan queue:work
開啟常駐內(nèi)存服務(wù)
若在Linux的常駐內(nèi)存:
nohup php artisan queue:work >> /dev/null &
5、在前端視圖中顯示