Skip to content

Commit

Permalink
归还连接 操作封装
Browse files Browse the repository at this point in the history
  • Loading branch information
itxiao6 committed Oct 9, 2020
1 parent 4798336 commit 2278975
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
8 changes: 4 additions & 4 deletions README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,10 @@ $s = microtime(true);
* 设置 回收数据库连接
*/
Swoole\Coroutine::defer(function () {
$lists = \itxiao6\SwooleDatabase\Utils\Context::get(\itxiao6\SwooleDatabase\PoolManager::class . '_connection') === null ? [] : \itxiao6\SwooleDatabase\Utils\Context::get(\itxiao6\SwooleDatabase\PoolManager::class . '_connection');
foreach ($lists as $item) {
\itxiao6\SwooleDatabase\PoolManager::getPool($item['name'])->put($item['pdo']);
}
/**
* 归还当前协程内的连接
*/
\itxiao6\SwooleDatabase\PoolManager::recoveryConnection();
});
/**
* 创建表
Expand Down
22 changes: 18 additions & 4 deletions src/PoolManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@


namespace itxiao6\SwooleDatabase;

use Swoole\Database\PDOPool;

/**
* 连接池管理(全局)
* Class PoolManager
Expand All @@ -18,9 +20,9 @@ class PoolManager
* @param string $name
* @throws \Exception
*/
public static function addPool($size = 64,$name='default')
public static function addPool($size = 64, $name = 'default')
{
if(isset(self::$pool[$name]) && self::$pool[$name] instanceof PDOPool){
if (isset(self::$pool[$name]) && self::$pool[$name] instanceof PDOPool) {
throw new \Exception('Pool Exist');
}
$config = PDOConfig::getConfig($name);
Expand All @@ -33,11 +35,23 @@ public static function addPool($size = 64,$name='default')
* @return PDOPool
* @throws \Exception
*/
public static function getPool($name='default')
public static function getPool($name = 'default')
{
if(!(isset(self::$pool[$name]) && self::$pool[$name] instanceof PDOPool)){
if (!(isset(self::$pool[$name]) && self::$pool[$name] instanceof PDOPool)) {
self::addPool();
}
return self::$pool[$name];
}

/**
* 归还当前协程内的所有连接
* @throws \Exception
*/
public static function recoveryConnection()
{
$lists = \itxiao6\SwooleDatabase\Utils\Context::get(\itxiao6\SwooleDatabase\PoolManager::class . '_connection') === null ? [] : \itxiao6\SwooleDatabase\Utils\Context::get(\itxiao6\SwooleDatabase\PoolManager::class . '_connection');
foreach ($lists as $item) {
\itxiao6\SwooleDatabase\PoolManager::getPool($item['name'])->put($item['pdo']);
}
}
}

0 comments on commit 2278975

Please sign in to comment.