laravel

laravel之队列详解

2018-05-15  本文已影响20人  空气KQ

说明

laravel5.2,redis3

配置

就是把队列文件改成redis驱动
config/queue.php
.env修改即可

QUEUE_DRIVER=redis

生成任务类

php artisan make:job RedisTestQueue

生成文件
app\Jobs\RedisTestQueue.php
这里我们注入redis
这里需要安装一下redis

composer require predis/predis ~1.0
<?php

namespace App\Jobs;

use Log;
use Redis;
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class RedisTestQueue extends Job implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;
    protected $redis_name;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($redis_name)
    {
        //
        $this->redis_name=$redis_name;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(Redis $redis)
    {

        $r=$redis::rPop($this->redis_name);

        $r?Log::info('del: '. $r .' is ok'):Log::info('del: '. $r .' is fail');;

    }
}

控制器写个Redis的列表的数据

Redis::Lpush($redis_name,'Kongqi','XiAo','YeYe','PengGe','DaLong','b','c','d','e','f');

浏览器去执行一个执行队列的任务访问

$job = (new RedisTestQueue($redis_name));
$this->dispatch($job);

执行之后,redis里面可以看到这个key

"queues:default"

这个是默认的命名
如果你这个时候执行,将会执行队列监听

php artisan queue:listen

为任务指定队列

$job = (new RedisTestQueue($redis_name))->onQueue('redis_test_queue');
$this->dispatch($job);

这个时候队列在redis会生成key

queues:redis_test_queue

执行这个指定的queue

php artisan queue:listen --queue=redis_test_queue

多个监听,优先级问题,左到右

php artisan queue:listen --queue=redis_test_queue,default

延迟任务,单位秒

$job = (new RedisTestQueue($redis_name))->delay(60);
$this->dispatch($job);

释放任务

手动释放任务
该方法接收一个参数——同一个任务两次运行之间的等待时间:

 $this->release(10);

尝试运行次数

$this->attempts()

推送任务到队列

控制器

$this->dispatch()


引入命名:Illuminate\Foundation\Bus\DispatchesJobs;

<?php

namespace App;

use Illuminate\Foundation\Bus\DispatchesJobs;

class ExampleClass{
    use DispatchesJobs;
    public function doJob(){
        $this->dispatch();
    }
}

方法
dispatch方法

dispatch(new App\Jobs\PerformTask);

任务事件

任务完成事件
Queue::after 方法允许你在队列任务执行成功后注册一个要执行的回调函数
这个AppServiceProvider里面书学,或者重新写一个提供者,可以参考提供者那篇文章
https://www.jianshu.com/p/f3fd1abeb5c9

<?php

namespace App\Providers;

use Queue;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Queue::after(function ($connection, $job, $data) {
            //
        });
        //后面2个参数,暂时没有测试出来,我发现后面都是空,所以应该写成
         Queue::after(function ($callback) {
            //
        });
      //#callback会返回出,我json下
      /*
      {
    "connectionName": "redis",
    "job": {},
    "data": {
        "job": "Illuminate\\Queue\\CallQueuedHandler@call",
        "data": {
            "commandName": "App\\Jobs\\RedisTestQueue",
            "command": "O:23:\"App\\Jobs\\RedisTestQueue\":5:{s:13:\"*redis_name\";s:11:\"queue:redis\";s:10:\"connection\";N;s:5:\"queue\";s:16:\"redis_test_queue\";s:5:\"delay\";N;s:6:\"*job\";N;}"
        },
        "id": "eWk75OXvL68uwDYmWIZYnRLXbvrNPzxH",
        "attempts": 1
    }
}
    */
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

失败任务事件,可参考上面

Queue::failing(function ($connection, $job, $data) {
            // Notify team of failing job...
 });

任务类的失败方法

 /**
     * 处理失败任务
     *
     * @return void
     */
    public function failed()
    {
        // Called when the job is failing...
    }

运行队列监听器

php artisan queue:listen

指定连接

php artisan queue:listen connection
//EXP
php artisan queue:listen redis

指定任务超时参数 --timeout=60,单位秒

php artisan queue:listen --timeout=60

队列睡眠时间

php artisan queue:listen --sleep=5

后台队列监听器

php artisan queue:work connection --daemon
php artisan queue:work connection --daemon --sleep=3
php artisan queue:work connection --daemon --sleep=3 --tries=3

如果你指定了队列名字,同样也是需要加入--queue='指定的名字'

 php artisan queue:work redis --queue=redis_test_queue --daemon

你要在任务完成之前释放资源

部署后台队列监听器

由于后台队列worker是常驻进程,不重启的话不会应用代码中的更改,所以,最简单的部署后台队列worker的方式是使用部署脚本重启所有worker,你可以通过在部署脚本中包含如下命令重启所有worker:

php artisan queue:restart

处理失败任务

创建一个failed_jobs表的迁移,可以使用queue:failed-table命令

php artisan queue:failed-table
php artisan migrate 

重试失败任务

//所有失败任务
php artisan queue:failed
//ID为5的重试
php artisan queue:retry 5 //执行ID为5的重试
//重试所有失败任务
php artisan queue:retry  all

删除一个失败任务

php artisan queue:forget 5
//删除所有
php artisan queue:flush
上一篇下一篇

猜你喜欢

热点阅读