1.配置.env决定使用哪种连接
QUEUE_CONNECTION=database此处的database会对应到config/queue.php的connections数组下面的键值 driver是队列使用的引擎 queue是队列名称 2.如果引擎是database,运行命令创建数据表 php artisan queue:table php artisan migrate
3.创建任务类 SendMail php artisan make:job SendMail 接着便能看到 app/Jobs/SendMail.php 我们只需要在handle方法做处理。比如我只是打印一下日志
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Log; class SendMail implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public $msg = ''; /** * Create a new job instance. * * SendMail constructor. * @param $msg */ public function __construct($msg) { $this->msg = $msg; } /** * Execute the job. * * @return void */ public function handle() { Log::info('Jobs SendMail'.$this->msg); } }4.在控制器使用任务 php artisan make:controller TestJobController 生成文件:app/Http/Controller/TestJobController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Jobs\SendMail; class TestJobController extends Controller { public function index(Request $request, $msg) { SendMail::dispatch($msg); } }然后配置路由访问控制器 routes/web.php
Route::get('/job/{msg}','TestJobController@index');5.最后,运行队列 php artisan queue:work 最后可以查看日志文件有没有打印
其他 (1)任务可以延迟执行、设置超时时间、运行期间运行抛出的异常次数、使用中间件等等。 (2)laravel有两个官方的拓展包可以直观地查看队列任务的执行情况Telescope、Horizon