扫码阅读
手机扫码阅读

Think-Swoole如何设置Swoole提供的配置项

135 2024-02-23

think-swoole 的文档极少,官方文档中也只是说了如何启动、热更新、连接池等配置,其他也没有说,可能需要看下源码。

今天 Swoole 微信交流群中有位同学说有内存泄漏,我试了一下确实是有内存泄漏的情况,而且裸用 think-swoole 也是有内存泄漏的

我们可以使用 Swoole 提供的max_request配置项临时解决一下内存泄漏

这个配置项的作用是当一个 worker 进程在处理完超过此数值的任务后将自动退出,进程退出后会释放所有内存和资源

配置项本来直接写在config/swoole.php中的server.options就可以了

我配置了一下这个参数之后,测试进程并没有重启,于是去看了一下 think-swoole 源码,发现底层直接写死为了 0

src/concerns/InteractsWithServer.php

public function run(): void{ $this->getServer()->set([ 'task_enable_coroutine' => true, 'send_yield'            => true, 'reload_async'          => true, 'enable_coroutine'      => true, 'max_request'           => 0, 'task_max_request'      => 0, ]); $this->initialize(); $this->triggerEvent('init');  //热更新 if ($this->getConfig('hot_update.enable', false)) { $this->addHotUpdateProcess(); }  $this->getServer()->start();}

询问了一下 ThinkPHP 开发组成员,得到的结果是:

设计就是这样的,希望这几个配置项固定成这样,所以写死了。同时防止 RPC 传文件时分多次上传,如果设置了就可能会出现传到一半的时候被重置了

同时给到了一个解决方法,就是通过事件去修改,即

$this->triggerEvent('init');

所以先来创建一个事件

php think make:listener SwooleInit

修改为以下内容

 declare(strict_types=1); namespace app\listener; use think\swoole\Manager; class SwooleInit{ public function handle(Manager $manager) { $manager->getServer()->set(['max_request' => 10]); // 或者使用下面这个 // app('think\swoole\Manager')->getServer()->set(['max_request' => 10]); }}

修改配置文件app\event.php

'listen' => [ 'swoole.init' => [\app\listener\SwooleInit::class],],

然后启动进行测试,就会发现修改成功了

原文链接: http://mp.weixin.qq.com/s?__biz=MzAwOTgzNjY4MA==&mid=2247483783&idx=1&sn=539ca0c177e6e76e3f017156580c0d28&chksm=9b58c060ac2f49769cf4765b999378070b3f1b134a9d28458190a48fc42839c9314a88fe93fc#rd