Supervisor自动管理Laravel事件队列

原创
2022/11/30 23:24
阅读数 49

首先使用artisan创建一个事件

php artisan make:event DoTest

此时在Events/目录下会生成一个DoTest文件

为这个事件创建一个监听器

php artisan make:listen DoTest

此时在Listeners/目录下会生成一个DoTest文件

我们让监听器监听DoTest事件

在Providers/EventServiceProvider.php文件中添加配置

        'App\Events\DoTest' => [
            'App\Listeners\DoTest',
        ],

我们来测试一下同步事件

首先我们在监听器中加入一行代码,后续这里都是一些业务逻辑

我们在监听器中写入一些数据

    public function handle($event)
    {
    ¦   $log = storage_path() . '/logs/dotest.log';
    ¦   file_put_contents($log, "dotest\r\n", FILE_APPEND | LOCK_EX);
    }

随便在一个脚本中调用事件

    protected function dotest()
    {
       try {
           $event = new DoTest();
           event($event);
        } catch (\Exception $e) {
           var_dump($e);
       }
    }

执行脚本

php artisan newcate:wechat dotest

查看日志文件:没错我们已经写入了一条数据

我们来测试一下异步事件

异步事件我们只需要在监听器中继承ShouldQueue即可

并指定一个数据库和队列名称

class DoTest implements ShouldQueue
{
    public $connection = 'redis';
    public $queue = '{do_test_event}';
    /**
    ¦* Create the event listener.
    ¦*
    ¦* @return void
    ¦*/
    public function __construct()
    {
    ¦   //
    }

    ...

}

此时我们在执行下脚本,发现并无新增数据

因为队列进程还未启动:ps aux | grep 'do_test_event'

打开进程配置文件:vim /etc/supervisord.d/laravel_work.ini

增加配置:

[group:events]do_test_event
[program:do_test_event]
process_name=%(program_name)s_%(process_num)02d
command=php /apps/webroot/reading-server/artisan queue:work redis --queue {do_test_event} --tries=3
autostart=true
autorestart=true
user=worker
numprocs=4
redirect_stderr=true
stdout_logfile=/apps/log/laravel/heya-reading.log

读取配置:supervisorctl reread

更新配置:supervisorctl update

启动进程:

supervisorctl 

start events:do_test_event_00

...

执行脚本:php artisan newcate:wechat dotest

发现日志数据已经有两条,do_test_event进程也已经开启

其他命令

supervisorctl:进入命令行交互界面,可直接输入子命令进行管理。

supervisorctl reload:重新加载配置文件,并重启supervisord及所有自动启动的程序。

supervisorctl restart {PROGRAM< ...>}|all:重启程序,all表示重启所有程序。

supervisorctl start {PROGRAM< ...>}|all:启动程序,all表示启动所有程序。

supervisorctl status <{PROGRAM< ...>}|all>:查看程序状态,如为all或不指定则查看所有程序状态。

supervisorctl stop {PROGRAM< ...>}|all:停止程序,all表示停止所有程序。

supervisorctl update:重新加载配置文件,并启动新配置指定的程序。

展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部