diff --git a/src/AbstractDbConnection.php b/src/AbstractDbConnection.php index 06bb856..ebab4de 100644 --- a/src/AbstractDbConnection.php +++ b/src/AbstractDbConnection.php @@ -97,4 +97,14 @@ protected function pushSqlToStack(string $sql) RequestContext::setContextDataByKey($contextSqlKey, $stack); } + + /** + * Verify whether the idle time exceeds the maximum value. + */ + protected function isIdleTimeOut(): bool + { + $idleTime = time() - $this->getLastTime(); + $maxIdleTime = $this->getPool()->getPoolConfig()->getMaxIdleTime(); + return $idleTime > $maxIdleTime; + } } diff --git a/src/Driver/Mysql/MysqlConnection.php b/src/Driver/Mysql/MysqlConnection.php index b035ad0..754faea 100644 --- a/src/Driver/Mysql/MysqlConnection.php +++ b/src/Driver/Mysql/MysqlConnection.php @@ -205,6 +205,9 @@ public function reconnect() */ public function check(): bool { + if ($this->isIdleTimeOut()) { + return false; + } return $this->connection->connected; } diff --git a/src/Driver/Mysql/SyncMysqlConnection.php b/src/Driver/Mysql/SyncMysqlConnection.php index d2273d2..034bfd3 100644 --- a/src/Driver/Mysql/SyncMysqlConnection.php +++ b/src/Driver/Mysql/SyncMysqlConnection.php @@ -124,6 +124,10 @@ public function reconnect() */ public function check(): bool { + if ($this->isIdleTimeOut()) { + return false; + } + try { $this->connection->getAttribute(\PDO::ATTR_SERVER_INFO); } catch (\Throwable $e) { diff --git a/test/Cases/PoolTest.php b/test/Cases/PoolTest.php index e4be5b2..de7eb22 100644 --- a/test/Cases/PoolTest.php +++ b/test/Cases/PoolTest.php @@ -14,6 +14,7 @@ use SwoftTest\Db\Testing\Pool\DbPptPoolConfig; use SwoftTest\Db\Testing\Pool\DbSlaveEnvPoolConfig; use SwoftTest\Db\Testing\Pool\DbSlavePptConfig; +use SwoftTest\Db\Testing\Pool\OtherDbPool; /** * PoolTest @@ -89,4 +90,37 @@ public function testDbSlaveEnv() $this->assertEquals($pConfig->isUseProvider(), false); $this->assertEquals($pConfig->getMaxWait(), 10); } + + public function testMaxIdleTime() + { + $pool = App::getPool('idle.master'); + $connection = $pool->getConnection(); + $this->assertTrue($connection->check()); + $connection->release(true); + $connection2 = $pool->getConnection(); + $this->assertTrue($connection2->check()); + $connection2->release(true); + } + + public function testMaxIdleTimeByCo() + { + go(function () { + $this->testMaxIdleTime(); + + $pool = App::getPool('idle.master'); + $connection = $pool->getConnection(); + $this->assertTrue($connection->check()); + $connection->release(true); + + \co::sleep(2); + + $connection2 = $pool->getConnection(); + $this->assertFalse($connection2->check()); + $connection2->release(true); + + $connection3 = $pool->getConnection(); + $this->assertTrue($connection3->check()); + $connection2->release(true); + }); + } } diff --git a/test/Testing/Pool/MaxIdleTimeDbConfig.php b/test/Testing/Pool/MaxIdleTimeDbConfig.php new file mode 100644 index 0000000..33bd9f2 --- /dev/null +++ b/test/Testing/Pool/MaxIdleTimeDbConfig.php @@ -0,0 +1,33 @@ +