laravel队列
2018年2月15日队列上不要使用模型我也不知道原因,总之不要使用
1配置和创建表
1 2 3 4 5 |
composer require "predis/predis:~1.0" //添加驱动 QUEUE_DRIVER=redis //配置驱动程序.env QUEUE_CONNECTION = sync //配置队列方式,sync为同步也就是关闭队列,线上填写redis php artisan queue:failed-table //队列失败表 database/migrations php artisan migrate //生成数据表 |
1.1如果使用mysql队列请将队列表设计为
1 2 3 4 5 6 7 8 9 |
Schema::create('jobs', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('queue')->index(); $table->longText('payload'); $table->unsignedTinyInteger('attempts'); $table->unsignedInteger('reserved_at')->nullable(); $table->unsignedInteger('available_at'); $table->unsignedInteger('created_at'); }); |
2创建队列任务
执行命令
1 |
php artisan make:job TranslateSlugJob // app/Jobs/TranslateSlugJob.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 |
<?php namespace App\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use App\Models\Topic; use App\Handlers\SlugTranslateHandler; class TranslateSlug implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; protected $topic; //这里构造数据 public function __construct(Topic $topic) { // 获取数据,并且写到topic中 $this->topic = $topic; } //这里主要些队列的方法 public function handle() { // 请求百度 API 接口进行翻译 $slug = app(SlugTranslateHandler::class)->translate($this->topic->title); // 为了避免模型监控器死循环调用,我们使用 DB 类直接对数据库进行操作 \DB::table('topics')->where('id', $this->topic->id)->update(['slug' => $slug]); } } |
3发布任务
1 2 3 4 5 |
//引入刚才创建的队列任务 use App\Jobs\TranslateSlugJob; // 推送任务到队列注意数据类型要和类中一致 dispatch(new TranslateSlugJob($topic)); |
4测试
1 |
php artisan queue:listen //开始测试 |
5后台运行
1 |
php artisan queue:work connection --daemon |