Skip to content

Commit

Permalink
feature: think pdo 支持分布式
Browse files Browse the repository at this point in the history
  • Loading branch information
krissss committed Mar 19, 2024
1 parent f448183 commit fdc57c6
Showing 1 changed file with 34 additions and 4 deletions.
38 changes: 34 additions & 4 deletions src/DataCollector/ThinkPdoCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,41 @@ public function __construct(array $thinkOrmConfig = [], TimeDataCollector $timeC
$connectionNames[] = $config['default'] ?? '';
$connectionNames = array_unique($connectionNames);

foreach ($connectionNames as $name) {
$connection = Db::connect($name);
foreach ($connectionNames as $connectionName) {
$connection = Db::connect($connectionName);
if ($connection instanceof PDOConnection) {
$pdo = $connection->connect();
$this->addConnection(new TraceablePDO($pdo), $name);
$dbConfig = $config['connections'][$connectionName] ?? [];
if (!empty($dbConfig['deploy'])) {
/**
* 分布式支持
* @link https://doc.thinkphp.cn/v8_0/distributed.html
* @see PDOConnection::multiConnect()
*/
$multiConfig = [];
foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) {
$dbConfig[$name] = $dbConfig[$name] ?? '';
$multiConfig[$name] = is_string($dbConfig[$name]) ? explode(',', $dbConfig[$name]) : $dbConfig[$name];
}
$multiDBConfig = [];
foreach ($multiConfig['hostname'] as $index => $hostname) {
$tempConfig = [];
foreach (['username', 'password', 'hostname', 'hostport', 'database', 'dsn', 'charset'] as $name) {
$tempConfig[$name] = $multiConfig[$name][$index] ?? $multiConfig[$name][0];
}
$multiDBConfig[] = [
'hostname' => $hostname,
'config' => $tempConfig,
];
}
foreach ($multiDBConfig as $index => $item) {
$pdo = $connection->connect($item['config'], $index);
$this->addConnection(new TraceablePDO($pdo), $connectionName . ':' . $item['hostname']);
}
} else {
// 单机
$pdo = $connection->connect();
$this->addConnection(new TraceablePDO($pdo), $connectionName);
}
}
}

Expand Down

0 comments on commit fdc57c6

Please sign in to comment.