This commit is contained in:
2023-08-29 21:54:02 +08:00
parent 9c8c8c6bb3
commit 5158b709bd
+35 -19
View File
@@ -143,10 +143,36 @@ class Connection extends Component
$length = $pool->size($this->cds); $length = $pool->size($this->cds);
for ($i = 0; $i < $length; $i++) { for ($i = 0; $i < $length; $i++) {
try { try {
$bool = $pool->get($this->cds); if (($client = $this->pop($pool, false)) === false) {
if ($bool === false) {
break; break;
} }
$pool->push($this->cds, [$client, time()]);
} catch (\Throwable $exception) {
if (!str_contains($exception->getMessage(), 'Client timeout.')) {
$this->logger->error(throwable($exception));
}
$pool->abandon($this->cds);
}
}
}
/**
* @param Pool $pool
* @param bool $isWaite
* @return PDO|bool
* @throws Exception
*/
protected function pop(Pool $pool, bool $isWaite): PDO|bool
{
if ($isWaite) {
$bool = $pool->get($this->cds, $this->waite_time);
} else {
$bool = $pool->get($this->cds);
}
if ($bool === false) {
return false;
}
/** @var PDO $client */ /** @var PDO $client */
[$client, $time] = $bool; [$client, $time] = $bool;
if ((time() - $time) > $this->idle_time) { if ((time() - $time) > $this->idle_time) {
@@ -155,12 +181,7 @@ class Connection extends Component
if ($client->query('select 1') === false) { if ($client->query('select 1') === false) {
throw new Exception($client->errorInfo()[1]); throw new Exception($client->errorInfo()[1]);
} }
$pool->push($this->cds, [$client, time()]); return $client;
} catch (\Throwable $exception) {
$this->logger->error(throwable($exception));
$pool->abandon($this->cds);
}
}
} }
@@ -202,23 +223,18 @@ class Connection extends Component
*/ */
protected function getNormalClientHealth(): PDO protected function getNormalClientHealth(): PDO
{ {
$data = $this->pool()->get($this->cds, $this->waite_time); try {
$data = $this->pop($this->pool(), true);
if ($data === false) { if ($data === false) {
throw new Exception('Pool waite timeout at ' . $this->waite_time); throw new Exception('Pool waite timeout at ' . $this->waite_time);
} }
return $data;
[$client, $time] = $data; }catch (\Throwable $exception) {
if ((time() - $time) < $this->idle_time && $this->canUse($client)) { $this->logger->error($exception->getMessage(), [$this->cds]);
return $client;
}
$client = null;
$data = null;
$this->logger->error('PDO连接已失效, 空闲超时或已不可用,重新获取.', [$this->cds]);
$this->pool()->abandon($this->cds); $this->pool()->abandon($this->cds);
return $this->getNormalClientHealth(); return $this->getNormalClientHealth();
} }
}
/** /**