一、配置檔案
首先我們需要在配置檔案中配置預設隊列驅動為Redis,隊列配置檔案是config/queue.php:
return [
'default' => env('QUEUE_DRIVER', 'sync'),
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'expire' => 60,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'ttr' => 60,
],
'sqs' => [
'driver' => 'sqs',
'key' => 'your-public-key',
'secret' => 'your-secret-key',
'queue' => 'your-queue-url',
'region' => 'us-east-1',
],
'iron' => [
'driver' => 'iron',
'host' => 'mq-aws-us-east-1.iron.io',
'token' => 'your-token',
'project' => 'your-project-id',
'queue' => 'your-queue-name',
'encrypt' => true,
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => 'default',
'expire' => 60,
],
],
'failed' => [
'database' => 'mysql', 'table' => 'failed_jobs',
],
];
複制
該配置檔案第一個配置項default用于指定預設的隊列驅動,這裡我們将其值改為redis(實際上是修改.env中的QUEUE_DRIVER)。
複制
二、編寫隊列任務
首先我們通過如下Artisan指令建立任務類:
php artisan make:job SendReminderEmail
運作成功後會在app/Jobs目錄下生成一個SendReminderEmail.php,我們修改其内容如下:
<?php
namespace App\Jobs;
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\User;
use Illuminate\Contracts\Mail\Mailer;
class SendReminderEmail extends Job implements SelfHandling, ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $user;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Execute the job.
*
* @return void
*/
public function handle(Mailer $mailer)
{
$user = $this->user;
$mailer->send('emails.reminder',['user'=>$user],function($message) use ($user){
$message->to($user->email)->subject('新功能釋出');
});
}
}
複制
三、推送隊列任務
手動分發任務
我們可以使用控制器中的DispatchesJobs trait(該trait在控制器基類Controller.php中引入)提供的dispatch方法手動分發任務:
//在控制器中use
use App\Jobs\SendReminderEmail;
接着直接調用就是了
$user = App\User::findOrFail($id);
$this->dispatch(new SendReminderEmail($user));
複制
四、運作隊列監聽器
在浏覽器中通路http://laravel.app:8000/mail/sendReminderEmail/1,此時任務被推送到Redis隊列中,我們還需要在指令行中運作Artisan指令執行隊列中的任務。Laravel為此提供了三種Artisan指令:
queue:work 預設隻執行一次隊列請求, 當請求執行完成後就終止;
queue:listen 監聽隊列請求,隻要運作着,就能一直接受請求,除非手動終止;
queue:work --daemon 同 listen 一樣, 隻要運作着,就能一直接受請求,不一樣的地方是在這個運作模式下,當新的請求到來的時候,不重新加載整個架構,而是直接 fire 動作。能看出來, queue:work --daemon是最進階的,一般推薦使用這個來處理隊列監聽。
注:使用 queue:work --daemon ,當更新代碼的時候,需要停止,然後重新啟動,這樣才能把修改的代碼應用上。
是以我們接下來在指令行中運作如下指令:
php artisan queue:work --daemon