Skip to content

Commit

Permalink
修复因 PHP cURL bug 导致的内存泄漏问题
Browse files Browse the repository at this point in the history
  • Loading branch information
Yurunsoft committed Jan 31, 2020
1 parent a510b59 commit 3fbebb0
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 9 deletions.
1 change: 1 addition & 0 deletions src/HttpRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@ public function open()
*/
public function close()
{
$this->handler->close();
$this->handler = null;
}

Expand Down
14 changes: 6 additions & 8 deletions src/YurunHttp/Handler/Curl.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,12 @@ public function __construct()
$this->initCookieManager();
}

public function __destruct()
/**
* 关闭并释放所有资源
*
* @return void
*/
public function close()
{
if($this->handler)
{
Expand Down Expand Up @@ -131,8 +136,6 @@ public function send($request)
$uri = $this->request->getUri();
$isLocation = false;
$statusCode = 0;
$lastMethod = null;
$copyHandler = curl_copy_handle($this->handler);
$redirectCount = 0;
do{
// 请求方法
Expand All @@ -152,12 +155,7 @@ public function send($request)
{
$bodyContent = false;
}
if($lastMethod && 'GET' !== $lastMethod && 'GET' === $method)
{
$this->handler = curl_copy_handle($copyHandler);
}
$this->buildCurlHandlerEx($this->request, $this->handler, $uri, $method, $bodyContent);
$lastMethod = $method;
$retry = $this->request->getAttribute(Attributes::RETRY, 0);
for($i = 0; $i <= $retry; ++$i)
{
Expand Down
7 changes: 7 additions & 0 deletions src/YurunHttp/Handler/IHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,11 @@ public function getHandler();
*/
public function coBatch($requests, $timeout = null);

/**
* 关闭并释放所有资源
*
* @return void
*/
public function close();

}
7 changes: 6 additions & 1 deletion src/YurunHttp/Handler/Swoole.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,12 @@ public function __construct()
$this->http2ConnectionManager = new Http2ConnectionManager;
}

public function __destruct()
/**
* 关闭并释放所有资源
*
* @return void
*/
public function close()
{
$this->httpConnectionManager->close();
$this->http2ConnectionManager->close();
Expand Down
15 changes: 15 additions & 0 deletions tests/unit/HttpRequestTest/HttpRequestTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -480,4 +480,19 @@ public function testCoBatch()
});
}

public function testMemoryLeak()
{
$this->call(function(){
$memorys = [1, 2, 3, 4, 5];
for($i = 0; $i < 5; ++$i)
{
$http = new HttpRequest;
$http->get($this->host);
$memorys[$i] = memory_get_usage();
}
unset($memorys[0]);
$this->assertEquals(1, count(array_unique($memorys)));
});
}

}

0 comments on commit 3fbebb0

Please sign in to comment.