laravel 队列queue

队列

Laravel队列服务为各种不同的后台队列提供统一的API

允许推迟耗时任务(例如发送邮件)的执行,从而大幅提高web请求速度

 

配置文件

Config/queue.php

支持模式 Supported: "sync", "database","beanstalkd", "sqs", "redis",

//默认选择的是同步驱动

'default' =>env('QUEUE_DRIVER', 'sync'),

步骤(以database发送邮件为例)

1.    迁移队列需要的数据表

a.     修改env里的QUEUE_DRIVER=database

 

b.     生成迁移php artisan queue:table

Migration created successfully!

可在database/migrations里看到一个create_jobs_table.php

 

c.      执行php artisan migrate

Migrating:2017_09_30_092257_create_jobs_table

Migrated:  2017_09_30_092257_create_jobs_table

2.    编写任务类

生成任务php artisan make:job SendEmail

Job created successfully.

可在app/jobs里看到一个SendEmail.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 Mail;
class SendEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $email;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($email)
    {
        $this->email = $email;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
         Mail::raw('邮件内容', function($message) {
            //收件人
            $message->to($this->email);
        });
    }
}

3.    推送任务到队列

Controller

public function queue()
{
    //dispatch 已经基础controller里已经引用
    dispatch(new SendEmail('827599490@qq.com'));
}

这时可以打开数据库看一下,数据库里会多一条,这时已经成功

4.    运行队列监听器

执行命令php artisan queue:listen

[2017-09-30 09:39:06] Processing:App\Jobs\SendEmail

监听中了,这时可以运行 controller 下的queue看下效果了

5.    处理失败任务

添加失败表

a.生成迁移php artisan queue:failed-table

Migration created successfully!

可在database/migrations里看到一个create_failed_jobs_table.php

 

b.执行php artisan migrate

Migrating: 2017_09_30_092257_ failed_create_jobs_table

Migrated:  2017_09_30_092257_ failed_create_jobs_table

数据库里多了failed_create_jobs

 

操作执行错误的记录

查看所有错误php artisan queue:failed

执行错误ID为1的记录 php artisan queue:retry 1

执行所有错误php artisan queue:retry all

删除错误ID为4的记录 php artisan queue:forget failed 4

删除所有错误 php artisan queue:forget flush

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值