官方文档http://laravel.com/docs/5.1/queues#dealing-with-failed-jobs
1、队列容器设置为数据库
config/queue.php
'default' => env('QUEUE_DRIVER', 'database'),
2、建立队列和失败队列数据库
php artisan queue:table
php artisan queue:failed-table
php artisan migrate
3、创建队列SendReminderEmail
php artisan make:job SendReminderEmail --queued
<?php namespace AppJobs; use AppUser; use AppJobsJob; use IlluminateQueueSerializesModels; use IlluminateQueueInteractsWithQueue; use IlluminateContractsBusSelfHandling; use IlluminateContractsQueueShouldQueue; use IlluminateSupportFacadesMail; use Exception; class SendReminderEmail extends Job implements SelfHandling, ShouldQueue { use InteractsWithQueue, SerializesModels; protected $user; public function __construct(User $user) { $this->user = $user; } public function handle() { $user = $this->user; $url = route('confirmation', ['token' => $user->registration_token]); Mail::send('emails/registration', compact('user', 'url'), function ($m) use ($user) { $m->to($user->email, $user->name)->subject('test!'); }); // throw new Exception; //异常可使队列失败 } }
4、发送队列
<?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppHttpRequests; use AppHttpControllersController; use AppUser; use AppJobsSendReminderEmail; class JobsController extends Controller { public function testSendJobs(){ $user = User::findOrFail(1); $this->dispatch(new SendReminderEmail($user)); } }
5、开启队列监听
php artisan queue:listen database --tries=3 //监听数据库容器的队列,3次执行失败,则将队列放到失败队列数据库表
6、处理失败队列
php artisan queue:failed //列出失败队列 php artisan queue:retry 1 //将id=1的失败队列恢复到队列表
关于消息队列的补充
原生的redis消息队列,一般用list列表,lPush进列生产,rpop出列消费模式,用php-cli系统计划任务模式执行消费脚本。
关于redis应用场景
接口数据缓存,队列保存等