laravel8中队列

1、创建model 

  php artisan make:model Podcast 

2、创建迁移文件

  php artisan make:migration podcasts

       在生成的迁移文件里创建两个字段 id & status ,database目录下新建表的 run 方法:

public function up()
{
  Schema::create('podcasts', function (Blueprint $table) {
    $table->increments('id');
    $table->tinyInteger('status')->unsigned();
    $table->timestamps();
  });
}

3、创建控制器,增加 store 方法

  php artisan make:controller PodcastController

  增加一个store方法
  public function store( ) {
    $model = new Podcast();
    $model->status = 0;
    $model->save();
    ProcessPodcast::dispatch($model)->delay(now()->addMinutes(3));
  }

4、生成 Job / ProcessPodcast.php 类

  php artisan make:job ProcessPodcast

  内容如下

<?php

namespace App\Jobs;

use App\Models\Podcast;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ProcessPodcast implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $podcast;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(Podcast $podcast)
    {
        $this->podcast = $podcast;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $this->podcast->status = 1;
        $this->podcast->update();
    }
}

5、配置 .env

QUEUE_CONNECTION=redis
(注:需要先配置好redis链接)

6、在 routes/web.php 增加路由

Route::get(
    '/queue',
    [PodcastController::class, 'store']
);

7、在服务器上执行 php artisan queue:work 

 

 

原文链接:https://learnku.com/laravel/t/32097

posted @ 2022-02-28 16:45  艾薇-Ivy  阅读(192)  评论(0编辑  收藏  举报