美文网首页
Laravel中使用队列

Laravel中使用队列

作者: RwatitFahsa | 来源:发表于2018-12-21 18:17 被阅读22次

    Laravel中使用队列

    官方教程

    ## 安装依赖扩展包

    composer require"predis/predis ~1.0"

    ## 在.env中配置

    QUEUE_DRIVER=rdeis

    ## 配置表

    php artisan queue:failed-table

    ## 在datebase下修改

    publicfunctionup()

       {

    Schema::create('h_queue_failed',function(Blueprint$table) {

    $table->bigIncrements('id');

    $table->text('connection');

    $table->text('queue');

    $table->longText('payload');

    $table->longText('exception');

    $table->timestamp('failed_at')->useCurrent();

           });

       }

    ## 生成记录失败的数据库表

    php artisan migrate

    ## 生成一个任务类(队列的job worker)

    php artisanmake:job SendSms

    ## 在 app/Jobs/ 目录下出现了对应的 worker 文件 SendSms.php

    class SendSms implements ShouldQueue

    {

       use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected$number;

       /**

        * Create a new job instance.

        *

        * @return void

        */

    publicfunction__construct($number)

       {

    $this->number=$number;

       }

       /**

        * Execute the job.

        *

        * @return void

        */

    publicfunctionhandle()

       {

    Log::info('This is an sms sent to '.$this->number);

       }

    }

    ## 该类实现了 Illuminate\Contracts\Queue\ShouldQueue 接口,该接口表明 Laravel 应该将该任务添加到后台的任务队列中,而不是同步执行。

    ## handle 方法会在队列任务执行时被调用。值得注意的是,我们可以在任务的 handle 方法中可以使用类型提示来进行依赖的注入。Laravel 的服务容器会自动的将这些依赖注入进去,与控制器方法类似。

    ## 还有一点需要注意,我们将会在模型监控器中分发任务,任务中要避免使用 Eloquent 模型接口调用,如:create(), update(), save() 等操作。否则会陷入调用死循环 —— 模型监控器分发任务,任务触发模型监控器,模型监控器再次分发任务,任务再次触发模型监控器.... 死循环。在这种情况下,使用 DB 类直接对数据库进行操作即可。

    ## 创建任务的 job seeder

    php artisanmake:controller SmsController

    ## 创建方法

    publicfunctionsendSms(Request$request){

    dispatch(New SendSms('13100000000'));

    return'send ok';

    }

    ## windows中启动redis

    redis-server redis.windows.conf

    ## app/Jobs 中只是定义了如何存储任务,而执行任务的需要我们手动启动

    php artisan queue:listen

    ## 注意: 这个服务起来之后,只会处理新到的任务,还是把历史没有处理完的任务都一次处理? 历史任务都会被处理。

    //dispatch(New SendSms('13100000000'));

    //延迟分发 例如:指定一个任务被分配后10分钟内不可被处理:

    dispatch(New SendSms('13243213456'))->delay(Carbon::now()->addMinute(10));

    //工作链

    //            SendSms::withChain([

    //                new OptimizePodcast,

    //                new ReleasePodcast

    //            ])->dispatch();

    //分发任务到指定队列中

    dispatch(new SendSms('1310000000'))->onQueue('hahah');

    //分发任务到指定连接

    //dispatch(new SendSms('1310000000'))->onConnection('sqs');

    //            ProcessPodcast::dispatch($podcast)

    //->onConnection('sqs')

    //->onQueue('processing');

    //你可以自定义队列处理器,方式是处理给定连接的特定队列。

    //举例来说,如果你所有的邮件都是在 redis 连接中的 emails 队列中处理的,你就能通过以下命令启动一个只处理那个特定队列的队列处理器了:

    // php artisan queue:work redis--queue=emails

    相关文章

      网友评论

          本文标题:Laravel中使用队列

          本文链接:https://www.haomeiwen.com/subject/lgevkqtx.html