记一次使用 Laravel Http Client 使用不当导致内存泄漏的问题 作者: Chuwen 时间: 2023-12-06 分类: PHP ## 背景 Laravel 的[ HTTP Client](https://laravel.com/docs/10.x/http-client " HTTP Client") 基于 Guzzle 二次封装,操作很方便,所以在业务代码上我就这么写了类似的代码 ```php $url = 'https://xxxx/xxx.json'; $json = Illuminate\Support\Facades\Http::get($url)->json(); // TODO 业务逻辑处理 ``` 项目使用了 [laravels](https://github.com/hhxsv5/laravel-s "laravels"),所以项目是常驻内存的,但是经过观察发 worker 内存会随着请求数量慢慢增加,并且不会自动回收内存,导致最终内存不足程序异常终止: ``` PHP Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 360448 bytes) in /Users/shine/work/xxxxxx-project/vendor/guzzlehttp/psr7/src/Utils.php on line 414 Symfony\Component\ErrorHandler\Error\FatalError Allowed memory size of 67108864 bytes exhausted (tried to allocate 360448 bytes) at vendor/guzzlehttp/psr7/src/Utils.php:414 410▕ }); 411▕ 412▕ try { 413▕ /** @var string|false $contents */ ➜ 414▕ $contents = stream_get_contents($stream); 415▕ 416▕ if ($contents === false) { 417▕ $ex = new \RuntimeException('Unable to read stream contents'); 418▕ } Whoops\Exception\ErrorException Allowed memory size of 67108864 bytes exhausted (tried to allocate 360448 bytes) at vendor/guzzlehttp/psr7/src/Utils.php:414 410▕ }); 411▕ 412▕ try { 413▕ /** @var string|false $contents */ ➜ 414▕ $contents = stream_get_contents($stream); 415▕ 416▕ if ($contents === false) { 417▕ $ex = new \RuntimeException('Unable to read stream contents'); 418▕ } +1 vendor frames 2 [internal]:0 Whoops\Run::handleShutdown() ``` ## 解决方案 通过研究框架代码,发现是没有正常关闭 Guzzle stream,导致内存一直累积无法回收 然后又在在 [vendor/laravel/framework/src/Illuminate/Http/Client/Response.php:247](https://github.com/laravel/framework/blob/10.x/src/Illuminate/Http/Client/Response.php#L247 "vendor/laravel/framework/src/Illuminate/Http/Client/Response.php:247") 位置发现有一个 `close()` 方法,但这个方法没有在任何地方使用,应该是想让你手动调用进行关闭 stream 所以将代码改成如下就可以了 ```php $url = 'https://xxxx/xxx.json'; $response = Illuminate\Support\Facades\Http::get($url); $json = $response->json(); // 关闭 stream $response->close(); // TODO 业务逻辑处理 ``` ## 附测试内存泄漏代码 ```php json(); printf("Count: %d\tPHP Memory: %.1fMB\n", $i++, memory_get_usage(true) / 1024.00 / 1024.00); } ``` ![](https://cdn.nowtime.cc/2023/12/06/138987942.png) ## 附测试修复内存泄漏后的代码 ```php body()) / 1024); $response->close(); } ``` ![](https://cdn.nowtime.cc/2023/12/06/3782614807.png) 标签: PHP, Laravel