laravel 队列
- 作者 : zfajax舫
- |
- 发布时间 : 6年前
- |
- 评论数 : 0
- 查看数 : 845
1配置和创建表
composer require "predis/predis:~1.1" //添加驱动
QUEUE_DRIVER=redis //配置驱动程序.env
QUEUE_CONNECTION = redis //配置队列方式,sync为同步也就是关闭队列,线上填写redis
php artisan queue:failed-table //队列失败表 database/migrations
php artisan migrate //生成数据表
1.1如果使用mysql队列请将队列表设计为
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创建队列任务
执行命令
php artisan make:job TranslateSlugJob // app/Jobs/TranslateSlugJob.php
开始编辑`app/Jobs/TranslateSlugJob.php`
<?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发布任务
//引入刚才创建的队列任务
use App\Jobs\TranslateSlugJob;
// 推送任务到队列注意数据类型要和类中一致
dispatch(new TranslateSlugJob($topic));
4测试
php artisan queue:listen //开始测试
5后台运行
php artisan queue:work connection --daemon
php artisan queue:listen //或者使用这个命令