Laravel队列使用案例

1、配置数据库和Redis
	//编辑config/database.php
	'mysql' => [
            'driver' => 'mysql',
            'host' => 'localhost',
            'port' => 3306,
            'database' => 'demo_laravel',
            'username' => 'demo',
            'password' => '123456',
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],
	'queue' => [
            'host' => '192.168.56.101',
            'password' => null,
            'port' => 6379,
            'database' => 0,
        ],
	//config/queue.php
	'default' => 'redis',
	'connections' => [
        'redis' => [
            'driver' => 'redis',
            'connection' => 'queue',
            'queue' => 'default',
            'expire' => 3600,//队列有效期
        ],

    ],
	'failed' => [
        'database' => 'mysql',
        'table' => 'failed_jobs',
    ],
2、添加failed-table
执行:php artisan queue:failed-table
执行:php artisan migrate:install
执行:php artisan migrate
3、生产者
将数据丢入队列
执行:php artisan make:console Demo/Test
<?php

namespace App\Console\Commands\Demo;

use App\Jobs\Demo\HandleTest;
use Illuminate\Console\Command;
use Illuminate\Foundation\Bus\DispatchesJobs;

class Test extends Command
{
    use DispatchesJobs;
    /**
     * 将数据丢入队列
     */
    protected $signature = 'demo:test {--num=}';
    protected $description = '将数据丢入队列';
    public function __construct()
    {
        parent::__construct();
    }
    public function handle()
    {
        $num = $this->option('num');
        for($i = 0; $i <= $num; $i++) {
            $queueName = 'demo_1';//这里可以按照业务取模之后启动多个队列
            $job = (new HandleTest($i))->onConnection('redis')->onQueue($queueName);
            $this->dispatch($job);
        }
    }
}


4、消费者
将消费队列内容
php artisan make:job Demo/HandleTest
app/Jobs/Demo/HandleTest.php
<?php

namespace App\Jobs\Demo;

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

class HandleTest extends Job implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;
    //初始化数据
    public function __construct($data)
    {
        $this->data = $data;
    }
    public function handle()
    {
        echo $this->data . PHP_EOL;
    }
}
5、启动生产者
php artisan demo:test --num=2
//这样可以看到redis的queues:demo_1
在redis执行:LRANGE queues:demo_1 0 -1
可以看到3个元素
6、启动消费队列(可以使用supervisor管理消费队列)
php artisan queue:work redis --queue=demo_1 --daemon --tries=10
7、队列失败
如果队列执行失败则会将任务存入failed_jobs表
重试JOB可以执行 php artisan queue:retry	1

Laravle Queue命令

php artisan queue:work --help
Usage:
  queue:work [options] [--] [<connection>]

Arguments:
  connection             队列连接redis、database等

Options:
      --queue[=QUEUE]    队列任务
      --daemon           后台执行
      --delay[=DELAY]    任务执行失败之后延迟多久重试
      --force            Force the worker to run even in maintenance mode
      --memory[=MEMORY]  The memory limit in megabytes [default: 128]
      --sleep[=SLEEP]    队列无可用任务休息时间间隔,默认3s
      --tries[=TRIES]    失败任务最多重试次数 [default: 0]
  -h, --help             输出帮助信息
  -q, --quiet            不输出信息
  -V, --version          Display this application version
      --ansi             Force ANSI output
      --no-ansi          Disable ANSI output
  -n, --no-interaction   Do not ask any interactive question
      --env[=ENV]        The environment the command should run under.
  -v|vv|vvv, --verbose   Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
使用案例
php artisan queue:work redis --queue=recommend --daemon --tries=1
备注:
queue:work 默认只执行一次队列请求, 当请求执行完成后就终止;
queue:listen 监听队列请求, 只要运行着, 就能一直接受请求, 除非手动终止;
queue:work --daemon 同 listen 一样, 只要运行着, 就能一直接受请求, 不一样的地方是在这个运行模式下, 当新的请求到来的时候, 不重新加载整个框架, 而是直接 fire 动作.
能看出来, queue:work --daemon 是最高级的, 一般推荐使用这个来处理队列监听.

注意: 使用 queue:work --daemon , 当更新代码的时候, 需要停止, 然后重新启动, 这样才能把修改的代码应用上.
因此开发环境建议用queue:listen


php artisan queue:listen --help
Usage:
  queue:listen [options] [--] [<connection>]

Arguments:
  connection               The name of connection

Options:
      --queue[=QUEUE]      The queue to listen on
      --delay[=DELAY]      Amount of time to delay failed jobs [default: 0]
      --memory[=MEMORY]    The memory limit in megabytes [default: 128]
      --timeout[=TIMEOUT]  Seconds a job may run before timing out [default: 60]
      --sleep[=SLEEP]      Seconds to wait before checking queue for jobs [default: 3]
      --tries[=TRIES]      Number of times to attempt a job before logging it failed [default: 0]
  -h, --help               Display this help message
  -q, --quiet              Do not output any message
  -V, --version            Display this application version
      --ansi               Force ANSI output
      --no-ansi            Disable ANSI output
  -n, --no-interaction     Do not ask any interactive question
      --env[=ENV]          The environment the command should run under.
  -v|vv|vvv, --verbose     Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug