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 @   艾薇-Ivy  阅读(195)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示