一、配置文件
首先我們需要在配置文件中配置默認隊列驅動為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