一、配置文件
首先我们需要在配置文件中配置默认队列驱动为Redis,队列配置文件是config/queue.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 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命令创建任务类:
1 | php artisan make:job SendReminderEmail |
运行成功后会在app/Jobs目录下生成一个SendReminderEmail.php,我们修改其内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | <?phpnamespace 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方法手动分发任务:
1 2 | //在控制其中useuse App\Jobs\SendReminderEmail; |
接着直接调用就是了
1 2 | $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,当更新代码的时候,需要停止,然后重新启动,这样才能把修改的代码应用上。
所以我们接下来在命令行中运行如下命令:
1 | php artisan queue:work --daemon |