连接池
Kuiper Swoole 模块提供了高效的连接池实现,支持连接复用、健康检查、自动管理和性能监控。
连接池概述
连接池 (Connection Pool) 是一种创建和管理连接的技术,通过预先创建一组连接并重复使用这些连接来提高性能。
连接池的优势
- 减少连接创建开销: 连接创建是昂贵的操作,连接池可以复用已有连接
- 限制最大连接数: 防止创建过多连接导致资源耗尽
- 提高响应速度: 从池中获取连接比创建新连接快得多
- 自动管理: 自动处理连接的创建、复用、销毁
连接池架构
DefaultConnectionPool
├── PoolConfig (配置)
│ ├── min_connections - 最小连接数
│ ├── max_connections - 最大连接数
│ ├── connect_timeout - 连接超时
│ ├── wait_timeout - 等待超时
│ ├── heartbeat - 心跳间隔
│ └── health_check - 健康检查
├── Connection (连接对象)
│ ├── id - 连接 ID
│ ├── resource - 实际连接资源
│ └── createdAt - 创建时间
├── Channel (通道)
│ ├── Channel (协程通道)
│ └── SplQueueChannel (非协程队列)
└── PoolStatistics (统计)
├── active_connections - 活跃连接数
├── idle_connections - 空闲连接数
└── waiting_coroutines - 等待协程数PoolConfig (连接池配置)
配置选项
<?php
declare(strict_types=1);
use kuiper\swoole\pool\PoolConfig;
$config = new PoolConfig([
// 最小连接数 (默认: 1)
'min_connections' => 5,
// 最大连接数 (默认: 10)
'max_connections' => 20,
// 连接超时时间,单位: 秒 (默认: 10.0)
'connect_timeout' => 5.0,
// 等待连接超时时间,单位: 秒 (默认: 3.0)
'wait_timeout' => 3.0,
// 心跳间隔,单位: 秒 (默认: -1,不启用)
'heartbeat' => 60,
// 最大空闲时间,单位: 秒 (默认: -1,不限制)
'max_idle_time' => 300,
// 连接老化时间,单位: 秒 (默认: -1,不启用)
'aged_timeout' => 3600,
// 健康检查回调
'healthCheck' => new MyHealthCheck(),
// 连接预热回调
'warmup' => new MyWarmup(),
]);配置验证
PoolConfig 会自动验证配置的有效性:
<?php
declare(strict_types=1);
use kuiper\swoole\pool\PoolConfig;
// ✅ 有效配置
$config = new PoolConfig([
'min_connections' => 5,
'max_connections' => 20,
]);
// ❌ 无效配置 - min_connections > max_connections
try {
$config = new PoolConfig([
'min_connections' => 20,
'max_connections' => 10,
]);
} catch (\InvalidArgumentException $e) {
echo $e->getMessage();
// 输出: minConnections (20) cannot be greater than maxConnections (10)
}
// ❌ 无效配置 - max_connections 超出范围
try {
$config = new PoolConfig([
'max_connections' => 20000, // 超过最大值 10000
]);
} catch (\InvalidArgumentException $e) {
echo $e->getMessage();
}配置范围
| 参数 | 最小值 | 最大值 | 默认值 |
|---|---|---|---|
| min_connections | 0 | 1000 | 1 |
| max_connections | 1 | 10000 | 10 |
| connect_timeout | > 0 | 300 | 10.0 |
| wait_timeout | > 0 | 300 | 3.0 |
| heartbeat | -1 或 > 0 | 86400 | -1 |
| max_idle_time | -1 或 > 0 | 86400 | -1 |
| aged_timeout | -1 或 > 0 | 86400 | 300 |
connect_timeout与wait_timeout的下界是严格大于 0——校验器为$v > 0.0 && $v <= 300.0,传0会抛InvalidArgumentException: Invalid value for connectTimeout: 0. ...。heartbeat/max_idle_time/aged_timeout允许-1(表示不限),否则同样要求> 0。
aged_timeout默认 300 秒(连接最长存活时间,超时后归还时销毁重建),-1表示永不过期。 注意heartbeat与max_idle_time目前仅作为 PoolConfig 的合法键存在,框架内部尚未消费(预留配置)。越界取值、未知键、以及
min_connections > max_connections都会在PoolConfig构造期抛\InvalidArgumentException(见 v0.9.4 迁移说明 M32)。
DefaultConnectionPool (默认连接池)
创建连接池
<?php
declare(strict_types=1);
use kuiper\swoole\pool\DefaultConnectionPool;
use kuiper\swoole\pool\PoolConfig;
// 创建配置
$config = new PoolConfig([
'min_connections' => 2,
'max_connections' => 10,
'connect_timeout' => 5.0,
'wait_timeout' => 3.0,
]);
// 创建连接池
$pool = new DefaultConnectionPool(
'my-pool', // 连接池名称
function (int $connId, mixed &$resource = null) {
// 连接工厂函数
$connection = new PDO(
'mysql:host=localhost;dbname=test',
'user',
'password'
);
return $connection;
},
$config
);获取和释放连接
<?php
declare(strict_types=1);
use kuiper\swoole\pool\DefaultConnectionPool;
use kuiper\swoole\pool\PoolConfig;
use kuiper\swoole\coroutine\Coroutine;
\Swoole\Coroutine\run(function () {
$pool = new DefaultConnectionPool(
'db-pool',
function (int $connId) {
return new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
},
new PoolConfig(['max_connections' => 10])
);
// 获取连接
$connection = $pool->take();
try {
// 使用连接
$stmt = $connection->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([1]);
$result = $stmt->fetch();
var_dump($result);
} finally {
// 释放连接(协程环境下会自动释放)
$pool->release($connection);
}
});自动释放 (协程环境)
在协程环境中,连接会自动释放:
<?php
declare(strict_types=1);
use kuiper\swoole\pool\DefaultConnectionPool;
use kuiper\swoole\pool\PoolConfig;
\Swoole\Coroutine\run(function () {
$pool = new DefaultConnectionPool(
'db-pool',
function (int $connId) {
return new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
},
new PoolConfig(['max_connections' => 10])
);
// 获取连接
$connection = $pool->take();
// 使用连接
$result = $connection->query('SELECT * FROM users');
// 协程结束时自动释放连接,无需手动调用 release
});连接创建
连接工厂函数
连接工厂函数负责创建实际的连接资源:
<?php
declare(strict_types=1);
use kuiper\swoole\pool\DefaultConnectionPool;
// 简单工厂函数
$pool = new DefaultConnectionPool(
'db-pool',
function (int $connId) {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
},
$config
);
// 带引用参数的工厂函数
$pool = new DefaultConnectionPool(
'db-pool',
function (int $connId, &$resource = null) {
$resource = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
// 可以返回 bool 表示成功/失败
return true;
},
$config
);连接初始化
连接池会在创建时预创建最小数量的连接:
<?php
declare(strict_types=1);
use kuiper\swoole\pool\DefaultConnectionPool;
use kuiper\swoole\pool\PoolConfig;
$config = new PoolConfig([
'min_connections' => 5, // 预创建 5 个连接
'max_connections' => 20,
]);
$pool = new DefaultConnectionPool(
'db-pool',
function (int $connId) {
echo "创建连接 #{$connId}\n";
return new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
},
$config
);
// 输出:
// 创建连接 #1
// 创建连接 #2
// 创建连接 #3
// 创建连接 #4
// 创建连接 #5连接复用
连接复用机制
<?php
declare(strict_types=1);
use kuiper\swoole\pool\DefaultConnectionPool;
use kuiper\swoole\pool\PoolConfig;
\Swoole\Coroutine\run(function () {
$pool = new DefaultConnectionPool(
'db-pool',
function (int $connId) {
echo "创建连接 #{$connId}\n";
return new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
},
new PoolConfig(['min_connections' => 1, 'max_connections' => 3])
);
// 第一次获取 - 创建新连接
$conn1 = $pool->take();
echo "获取连接 1\n";
// 释放连接
$pool->release($conn1);
echo "释放连接 1\n";
// 第二次获取 - 复用已释放的连接
$conn2 = $pool->take();
echo "获取连接 2 (复用连接 1)\n";
$pool->release($conn2);
});
// 输出:
// 创建连接 #1 (初始化时预创建)
// 获取连接 1
// 释放连接 1
// 获取连接 2 (复用连接 1)连接销毁
关闭连接池
<?php
declare(strict_types=1);
use kuiper\swoole\pool\DefaultConnectionPool;
$pool = new DefaultConnectionPool(
'db-pool',
function (int $connId) {
return new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
},
$config
);
// 使用连接池...
// 关闭连接池,释放所有连接
$pool->close();连接池监控
获取统计信息
<?php
declare(strict_types=1);
use kuiper\swoole\pool\DefaultConnectionPool;
$pool = new DefaultConnectionPool(
'db-pool',
function (int $connId) {
return new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
},
$config
);
// 获取活跃连接数
$activeCount = $pool->getActiveConnections();
echo "活跃连接: {$activeCount}\n";
// 获取空闲连接数
$idleCount = $pool->getIdleConnections();
echo "空闲连接: {$idleCount}\n";
// 获取等待协程数
$waitingCount = $pool->getWaitingCoroutines();
echo "等待协程: {$waitingCount}\n";
// 获取所有连接
$connections = $pool->getConnections();
echo "总连接数: " . count($connections) . "\n";连接池健康检查
<?php
declare(strict_types=1);
use kuiper\swoole\pool\PoolConfig;
use kuiper\swoole\pool\ConnectionHealthCheckInterface;
class DatabaseHealthCheck implements ConnectionHealthCheckInterface
{
public function isHealthy(mixed $connection): bool
{
try {
// 执行简单查询检查连接
$stmt = $connection->query('SELECT 1');
return $stmt->fetchColumn() === '1';
} catch (\Exception $e) {
return false;
}
}
}
$config = new PoolConfig([
'max_connections' => 10,
'healthCheck' => new DatabaseHealthCheck(),
]);连接池最佳实践
1. 合理设置连接数
// ✅ 根据实际负载设置
$config = new PoolConfig([
'min_connections' => 5, // 保持少量常驻连接
'max_connections' => 20, // 根据数据库服务器性能设置
]);
// ❌ 避免设置过大的连接数
$config = new PoolConfig([
'max_connections' => 10000, // 可能导致数据库服务器过载
]);2. 设置适当的超时
// ✅ 根据网络环境设置
$config = new PoolConfig([
'connect_timeout' => 5.0, // 5 秒连接超时
'wait_timeout' => 3.0, // 3 秒等待超时
]);
// ❌ 避免过长的超时
$config = new PoolConfig([
'connect_timeout' => 300, // 太长,影响用户体验
]);3. 启用健康检查
// ✅ 启用健康检查
$config = new PoolConfig([
'healthCheck' => new DatabaseHealthCheck(),
]);
// 定期检查连接健康状态
class DatabaseHealthCheck implements ConnectionHealthCheckInterface
{
public function isHealthy(mixed $connection): bool
{
try {
$connection->query('SELECT 1');
return true;
} catch (\Exception $e) {
return false;
}
}
}4. 使用连接预热
// ✅ 预热连接,提高首次使用性能
$config = new PoolConfig([
'warmup' => new class implements ConnectionWarmupInterface {
public function warmup(mixed $connection): void
{
// 执行初始化操作
$connection->query("SET time_zone='+00:00'");
$connection->query("SET NAMES utf8mb4");
}
},
]);5. 监控连接池状态
// ✅ 定期检查连接池状态
class PoolMonitor
{
public function __construct(
private readonly DefaultConnectionPool $pool
) {
}
public function logStatus(): void
{
echo "活跃连接: " . $this->pool->getActiveConnections() . "\n";
echo "空闲连接: " . $this->pool->getIdleConnections() . "\n";
echo "等待协程: " . $this->pool->getWaitingCoroutines() . "\n";
echo "平均等待时间: " . $this->pool->getAverageWaitTime() . "s\n";
}
}
// 定期监控
\Swoole\Coroutine\run(function () {
$monitor = new PoolMonitor($pool);
while (true) {
$monitor->logStatus();
\Swoole\Coroutine::sleep(60); // 每分钟检查一次
}
});异常处理
处理连接池异常
<?php
declare(strict_types=1);
use kuiper\swoole\pool\DefaultConnectionPool;
use kuiper\swoole\exception\PoolTimeoutException;
use kuiper\swoole\exception\PoolClosedException;
\Swoole\Coroutine\run(function () {
$pool = new DefaultConnectionPool(
'db-pool',
function (int $connId) {
return new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
},
new PoolConfig(['max_connections' => 2, 'wait_timeout' => 1.0])
);
try {
$connection = $pool->take();
// 使用连接...
$pool->release($connection);
} catch (PoolTimeoutException $e) {
echo "连接池超时: " . $e->getMessage() . "\n";
// 处理超时情况
} catch (PoolClosedException $e) {
echo "连接池已关闭: " . $e->getMessage() . "\n";
// 处理连接池关闭情况
} catch (\Exception $e) {
echo "其他错误: " . $e->getMessage() . "\n";
}
});连接代理(ConnectionProxyGenerator)
kuiper\swoole\pool\ConnectionProxyGenerator::create() 会为目标连接类生成一个 子类代理:代理方法经 PoolExecutor::withConnection() 借出真实连接、转发调用后 归还,调用方拿到的始终是同一个代理实例(见 RPC 与 Swoole 集成的「连接代理生成器」一节)。
<?php
use kuiper\swoole\pool\ConnectionProxyGenerator;
$client = ConnectionProxyGenerator::create(
$poolFactory,
\GuzzleHttp\ClientInterface::class,
static fn () => new \GuzzleHttp\Client()
);哪些类不可被代理
代理类无条件继承目标类,并自带 __construct(PoolInterface $pool) 与 __destruct()。因此以下目标类在生成期(ConnectionProxyGenerator::create() 与 generateProxyClass())直接抛 InvalidArgumentException,而不是产出一个 require 时必然 PHP 编译期致命错误(E_COMPILE_ERROR,不可 try/catch)的坏代理:
| 目标类情形 | 失败信息要点 |
|---|---|
final 类 | 不能被继承(Cannot extend final class) |
| 抽象类 | 不能实例化,且无法补齐非 public 抽象方法 |
含 final public 方法 | 代理无法覆盖 |
final 构造函数(final public function __construct()) | 代理声明的构造函数无法覆盖它 |
final 析构函数(final public function __destruct()) | 代理声明的析构函数无法覆盖它 |
private 构造 / 析构函数不会被继承,代理声明自己的实现不受影响,因此不在 检查之列。
可代理性校验发生在读取代理缓存之前:即使缓存命中(跳过代码生成),校验 依然执行——不可代理的目标类不会因为命中旧缓存而绕过检查。
缓存与失效
生成的代理文件落盘缓存(默认按进程用户隔离的临时目录,可用 create() 的 $cacheDir 参数指定)。缓存文件名掺入生成器版本号(GENERATOR_VERSION)与 目标类名的摘要:框架升级生成逻辑后旧代理文件不会被复用,首次运行会自动 重新生成。源类文件修改时间新于代理文件时同样重新生成。
返回类型支持
self/parent参数与返回类型统一解析为声明该方法的类的 FQCN;static返回类型保持原样(PHP 禁止子类把父类的static返回类型收窄成 具体类名),方法体把借到的连接实例转换成代理自身;- 可空性对所有类型保留——包括
?static(PHP 8.0 起合法)。此前版本生成?static时可空性被剥离成static,返回null会触发TypeError;升级 框架后旧代理文件因生成器版本号变化自动重新生成,无需手动清理缓存。
完整示例
数据库连接池服务
<?php
declare(strict_types=1);
use kuiper\swoole\pool\DefaultConnectionPool;
use kuiper\swoole\pool\PoolConfig;
use kuiper\swoole\pool\ConnectionHealthCheckInterface;
use kuiper\swoole\pool\ConnectionWarmupInterface;
class DatabaseConnectionPool
{
private DefaultConnectionPool $pool;
public function __construct(array $config)
{
$poolConfig = new PoolConfig([
'min_connections' => $config['min_connections'] ?? 2,
'max_connections' => $config['max_connections'] ?? 10,
'connect_timeout' => $config['connect_timeout'] ?? 5.0,
'wait_timeout' => $config['wait_timeout'] ?? 3.0,
'healthCheck' => new DatabaseHealthCheck(),
'warmup' => new DatabaseWarmup($config['init_sql'] ?? []),
]);
$this->pool = new DefaultConnectionPool(
'db-pool',
$this->createConnectionFactory($config),
$poolConfig
);
}
private function createConnectionFactory(array $config): callable
{
$dsn = sprintf(
'%s:host=%s;port=%d;dbname=%s;charset=%s',
$config['driver'] ?? 'mysql',
$config['host'] ?? 'localhost',
$config['port'] ?? 3306,
$config['database'],
$config['charset'] ?? 'utf8mb4'
);
return function (int $connId) use ($dsn, $config) {
$pdo = new PDO(
$dsn,
$config['username'] ?? 'root',
$config['password'] ?? '',
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_PERSISTENT => false,
]
);
return $pdo;
};
}
public function getConnection(): PDO
{
return $this->pool->take();
}
public function releaseConnection(PDO $connection): void
{
$this->pool->release($connection);
}
public function close(): void
{
$this->pool->close();
}
}
class DatabaseHealthCheck implements ConnectionHealthCheckInterface
{
public function isHealthy(mixed $connection): bool
{
try {
return false !== $connection->query('SELECT 1')->fetch();
} catch (\Exception $e) {
return false;
}
}
}
class DatabaseWarmup implements ConnectionWarmupInterface
{
public function __construct(
private readonly array $initSql
) {
}
public function warmup(mixed $connection): void
{
foreach ($this->initSql as $sql) {
try {
$connection->exec($sql);
} catch (\Exception $e) {
// 忽略预热错误
}
}
}
}
// 使用示例
\Swoole\Coroutine\run(function () {
$config = [
'host' => 'localhost',
'port' => 3306,
'database' => 'test',
'username' => 'root',
'password' => 'password',
'min_connections' => 2,
'max_connections' => 10,
'init_sql' => [
"SET time_zone='+00:00'",
"SET NAMES utf8mb4",
],
];
$pool = new DatabaseConnectionPool($config);
try {
$connection = $pool->getConnection();
$result = $connection->query('SELECT * FROM users LIMIT 10');
foreach ($result as $row) {
echo $row['name'] . "\n";
}
$pool->releaseConnection($connection);
} finally {
$pool->close();
}
});性能对比
无连接池 vs 有连接池
测试场景: 执行 1000 次数据库查询
无连接池:
- 每次查询创建新连接
- 总耗时: ~15 秒
- 内存占用: 低
有连接池:
- 复用 10 个连接
- 总耗时: ~3 秒
- 内存占用: 中
性能提升: 5 倍