Laravel PHP实战PHP经验分享

在 windows 下使用 Laravel 驱动消息队列

2017-03-21  本文已影响870人  wyrover

php 在 windows 下多进程不好使,没有 fork,不过你还是可以通过启动多个 php.exe 来执行脚本,把公共队列数据放在数据库或者 redis 下,然后排队访问。

不过这个东西已经由 Laravel 实现了,Laravel 提供了一个消息队列的投递和监听框架,消息队列的后端可以是

后面三种都是消息队列服务第三方组件,Laravel 在队列任务失败时,会把它存到数据库的 failed_jobs 表。

消息队列消费者

<?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;

class EchoTest implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        echo "hello queue world!" . $this->messageid_;
    }

    protected $messageid_;
}

消息队列数据生产者

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Foundation\Bus\DispatchesJobs;
use App\Jobs\EchoTest;

class TestDb extends Command
{
    use DispatchesJobs;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'testdb {--queue}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $options = $this->options();
        $queueName = $this->option('queue');
        $this->info('hello world!');
        $this->info('中文测试');
        $this->error('something went wrong!');

        $this->info('通过命令行执行队列任务');

        for ($i = 0; $i < 1000; ++$i) {
            $this->dispatch((new EchoTest($i))->onQueue('echo'));
        }



    }
}

修改 .env 配置

QUEUE_DRIVER=database

运行一个消息队列监听进程

cd /d H:\laravel_cmd_test
php artisan queue:work database --daemon --queue=echo

运行消息队列生产者命令行

php artisan testdb

为什么要在 windows 下使用 laravel 实现消息队列

添加批处理命令行启动多个消费者进程

** run-sub-daemon.bat **

title %1
cd /d "%~dp0" 
@path=%~dp0\tools;%path%
CALL "%~dp0\setenv.bat"
cd /d "%~dp0"


cd db_test\laravel_cmd_test
php artisan queue:work database --daemon --queue=echo

run-daemon.bat

@echo off
setlocal enabledelayedexpansion
:main
for /l %%i in (1,1,5) do (
set n=%%i
start "" "run-sub-daemon.bat" 队列子进程!n!
)

双击运行 run-daemon.bat,打开 5 个队列消费者进程。

然后运行 laravel 命令行 php artisan testdb,开始狂奔吧!

![$O{LJ_UR7}WWOKK2O}BDC]A.png](http:https://img.haomeiwen.com/i1111419/e62d6ec4e61a2471.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

links

上一篇 下一篇

猜你喜欢

热点阅读