官方文档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 App\Jobs; use App\User;
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Mail;
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 App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests;
use App\Http\Controllers\Controller; use App\User;
use App\Jobs\SendReminderEmail; class JobsController extends Controller
{
public function testSendJobs(){
$user = User::findOrFail();
$this->dispatch(new SendReminderEmail($user)); }
}
5、开启队列监听
php artisan queue:listen database --tries= //监听数据库容器的队列,3次执行失败,则将队列放到失败队列数据库表
6、处理失败队列
php artisan queue:failed //列出失败队列
php artisan queue:retry //将id=1的失败队列恢复到队列表
关于消息队列的补充
原生的redis消息队列,一般用list列表,lPush进列生产,rpop出列消费模式,用php-cli系统计划任务模式执行消费脚本。
关于redis应用场景
接口数据缓存,队列保存等