編程學(xué)習(xí)網(wǎng) > PHP技術(shù) > swoole > 裸用think-swoole出現(xiàn)內(nèi)存泄漏怎么辦?
2021
08-09

裸用think-swoole出現(xiàn)內(nèi)存泄漏怎么辦?

在論壇上看到有小伙伴說有內(nèi)存泄漏,我試了一下確實是有內(nèi)存泄漏的情況,而且裸用 think-swoole 也是有內(nèi)存泄漏的,所以本文就給大家分享一下如果裸用think-swoole出現(xiàn)內(nèi)存泄漏怎么辦?

解決方法:可以使用 Swoole 提供的max_request配置項臨時解決一下內(nèi)存泄漏


這個配置項的作用是當(dāng)一個 worker 進(jìn)程在處理完超過此數(shù)值的任務(wù)后將自動退出,進(jìn)程退出后會釋放所有內(nèi)存和資源


配置項本來直接寫在config/swoole.php中的server.options就可以了


我配置了一下這個參數(shù)之后,測試進(jìn)程并沒有重啟,于是去看了一下 think-swoole 源碼,發(fā)現(xiàn)底層直接寫死為了 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 開發(fā)組成員,得到的結(jié)果是:

設(shè)計就是這樣的,希望這幾個配置項固定成這樣,所以寫死了。同時防止 RPC 傳文件時分多次上傳,如果設(shè)置了就可能會出現(xiàn)傳到一半的時候被重置了

同時給到了一個解決方法,就是通過事件去修改,即

$this->triggerEvent('init');

所以先來創(chuàng)建一個事件


php think make:listener SwooleInit

修改為以下內(nèi)容


<?php

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],

],

然后啟動進(jìn)行測試,就會發(fā)現(xiàn)修改成功了

以上就是“裸用think-swoole出現(xiàn)內(nèi)存泄漏怎么辦?”的詳細(xì)內(nèi)容,想要了解更多關(guān)于swoole教程歡迎關(guān)注編程學(xué)習(xí)網(wǎng)

掃碼二維碼 獲取免費視頻學(xué)習(xí)資料

Python編程學(xué)習(xí)

查 看2022高級編程視頻教程免費獲取