eee
This commit is contained in:
@@ -106,7 +106,8 @@ class MongoDB
|
||||
|
||||
|
||||
/**
|
||||
* 代理方法调用到 MongoDB Client
|
||||
* 代理方法调用到 MongoDB Client,内置连接健康检查和回收
|
||||
* 异常时关闭连接并回退计数器,防止断连对象污染连接池
|
||||
* @param $name
|
||||
* @param $arguments
|
||||
* @return mixed
|
||||
@@ -124,21 +125,53 @@ class MongoDB
|
||||
// 如果方法存在于 Database,通过默认数据库调用
|
||||
$database = $this->getDatabase();
|
||||
if (method_exists($database, $name)) {
|
||||
return $database->{$name}(...$arguments);
|
||||
$result = $database->{$name}(...$arguments);
|
||||
$this->returnClient($client);
|
||||
return $result;
|
||||
}
|
||||
|
||||
throw new \BadMethodCallException("Method {$name} does not exist on MongoDB Client or Database.");
|
||||
} catch (\Throwable $throwable) {
|
||||
\Kiri::getLogger()->json_log($throwable);
|
||||
|
||||
$this->closeClient($client);
|
||||
|
||||
return false;
|
||||
} finally {
|
||||
// MongoDB 连接是持久的,不需要释放
|
||||
$this->pool()->push($this->getName(), $client);
|
||||
}
|
||||
$this->returnClient($client);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 归还连接
|
||||
* @param Client $client
|
||||
* @return void
|
||||
*/
|
||||
private function returnClient(Client $client): void
|
||||
{
|
||||
try {
|
||||
$this->pool()->push($this->getName(), $client);
|
||||
} catch (\Throwable) {
|
||||
$this->closeClient($client);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 关闭连接并回退计数器
|
||||
* @param Client $client
|
||||
* @return void
|
||||
*/
|
||||
private function closeClient(Client $client): void
|
||||
{
|
||||
try {
|
||||
$client->close();
|
||||
} catch (\Throwable) {
|
||||
}
|
||||
$this->pool()->abandon($this->getName());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 执行 MongoDB 命令
|
||||
* @param array|object $command
|
||||
@@ -382,4 +415,3 @@ class MongoDB
|
||||
], $this->options);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -136,6 +136,8 @@ class Redis
|
||||
|
||||
|
||||
/**
|
||||
* 代理 Redis 方法调用,内置健康检查和连接回收
|
||||
* 如果连接 ping 失败则关闭连接并移除,不归还池中防止污染
|
||||
* @param $name
|
||||
* @param $arguments
|
||||
* @return mixed
|
||||
@@ -151,6 +153,9 @@ class Redis
|
||||
} finally {
|
||||
if ($client->ping('h') == 'h') {
|
||||
$this->pool()->push($this->getName(), $client);
|
||||
} else {
|
||||
$client->close();
|
||||
$this->pool()->abandon($this->getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user