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


Tagged , . Bookmark the permalink.

Comments are closed.