• Laravel 队列应用


    Laravel队列服务为各种不同的后台队列提供了统一的api。例如:允许推迟耗时任务(例如发送邮件)的执行,从而大幅提高web请求速度、

    步骤:

    1 迁移队列需要的数据表

    2 编写任务类

    3 推送任务到队列

    4 运行队列监听器

    5 处理失败的任务

    使用:

    1 配置

    configqueue.php

    支持的驱动类型:
     "sync", 同步驱动
     "database",数据库驱动
     "beanstalkd",
     "sqs",
     "redis",
     "null"

    失败配置:

    'failed' => [
            'driver' => env('QUEUE_FAILED_DRIVER', 'database'),
            'database' => env('DB_CONNECTION', 'mysql'),
            'table' => 'failed_jobs',
        ],
    QUEUE_CONNECTION=database

    2 创建迁移

    php artisan queue:table

    生成了一个迁移

    3 执行迁移

    php artisan migrate

    4 创建任务

    php artisan make:job SendEmail

    5 任务代码

    5.1 job
    appJobsSendEmail.php
    <?php
    
    namespace AppJobs;
    
    use IlluminateBusQueueable;
    use IlluminateContractsQueueShouldQueue;
    use IlluminateFoundationBusDispatchable;
    use IlluminateQueueInteractsWithQueue;
    use IlluminateQueueSerializesModels;
    use Mail;
    
    class SendEmail implements ShouldQueue
    {
        use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    
        protected $email;
        protected $subject;
    
        /**
         * Create a new job instance.
         *
         * @return void
         */
        public function __construct($email,$subject)
        {
            //
            $this->email = $email;
            $this->subject = $subject;
        }
    
        /**
         * Execute the job.
         *
         * @return void
         */
        public function handle()
        {
            //
            Mail::raw('队列测试',function ($message){
                $message
                    ->to($this->email)
                    ->subject($this->subject);
            });
        }
    }
    View Code
    5.2 控制器调用
    appHttpControllersStudentController.php
    use Log;
     public function queque()
        {
            $this->dispatch(new SendEmail('777777777@qq.com','队列测试'));
        }

    调用以后会在数据库里发现一行:

     6 执行

    php artisan queue:listen

     

    执行成功

    只要一直保持Listen状态

    再访问一下queque页面 又会执行一条。

    ps:执行完毕后,job表会被清空

    处理失败任务

    查看失败任务:
    php artisan queue:failed

     重新执行第1个任务
    php artisan queue:retry 1

     重新执行所有任务
    php artisan queue:retry all

    如果执行成功,会在failed表里删除

    不想执行失败的队列了

    根据id号删除

    php artisan queue:forget 2

    删除全部

    php artisan queue:flush
  • 相关阅读:
    ashx session
    jquery-tmpl中添加js判断
    问题与解决方案
    VS2013打包发布 winform程序
    Sorket通信
    加载页面菜单,原来也可以这么写
    pm2模块编写入门
    使用PouchDB来实现React离线应用
    让fetch也可以timeout
    使用JSON Schema来验证接口数据
  • 原文地址:https://www.cnblogs.com/polax/p/13406143.html
Copyright © 2020-2023  润新知