Private
Public Access
1
0

新增:MySQL 真连接池重构基础架构

核心改进:
- 创建 MySQLConnectionPool 真正的连接池实现
- 连接池配置结构 PoolConfig(可配置参数)
- 动态连接获取与释放机制
- 空闲连接自动清理
- 健康检查机制(定期 Ping)
- 慢连接日志记录
- 连接池统计信息(Stats)
- 维护协程(清理+健康检查)

新增文件:
- pool_config.go - 连接池配置和实现
  - PoolConfig: 可配置的连接池参数
  - MySQLConnectionPool: 真正的连接池
  - Acquire/Release: 连接获取与释放
  - 清理与维护协程

修改文件:
- pool.go - 集成新连接池到 ConnectionPool

技术特性:
- 默认配置:20最大连接 / 10最大空闲 / 2最小空闲
- 健康检查:30秒间隔
- 慢连接阈值:500ms
- 连接最大生命周期:30分钟
- 空闲超时:10分钟

TODO:
- 连接预热(启动时建立最小连接)
- LRU 连接复用策略
- 单元测试
- 性能基准测试
This commit is contained in:
2026-02-13 01:29:29 +08:00
parent ded8989fe3
commit bfe5226bfe
3 changed files with 467 additions and 2 deletions

View File

@@ -16,6 +16,10 @@ type ConnectionPool struct {
mysqlClients map[uint]*MySQLClient
redisClients map[uint]*RedisClient
mongoClients map[uint]*MongoClient
// 新增MySQL 真连接池
mysqlPool *MySQLConnectionPool
mu sync.RWMutex
}
@@ -27,20 +31,46 @@ var (
// GetPool 获取全局连接池实例
func GetPool() *ConnectionPool {
poolOnce.Do(func() {
// 创建 MySQL 连接池
poolConfig := DefaultPoolConfig()
mysqlPool := NewMySQLConnectionPool(poolConfig)
// 启动维护协程
mysqlPool.StartMaintenance()
globalPool = &ConnectionPool{
mysqlClients: make(map[uint]*MySQLClient),
redisClients: make(map[uint]*RedisClient),
mongoClients: make(map[uint]*MongoClient),
mysqlPool: mysqlPool,
}
})
return globalPool
}
// GetMySQLClient 获取或创建 MySQL 客户端
// GetMySQLClient 获取或创建 MySQL 客户端(使用连接池)
func (p *ConnectionPool) GetMySQLClient(conn *models.DbConnection) (*MySQLClient, error) {
p.mu.Lock()
defer p.mu.Unlock()
// 尝试从连接池获取连接
if p.mysqlPool != nil {
entry, err := p.mysqlPool.Acquire(conn)
if err == nil {
// 成功从池中获取连接
return entry.Client, nil
}
// 连接池错误,返回
return nil, err
}
// 降级到原有逻辑(如果连接池未初始化)
return p.getMySQLClientLegacy(conn)
}
// getMySQLClientLegacy 原有的 MySQL 客户端获取逻辑(向后兼容)
func (p *ConnectionPool) getMySQLClientLegacy(conn *models.DbConnection) (*MySQLClient, error) {
// 检查是否已存在
if client, ok := p.mysqlClients[conn.ID]; ok {
// 测试连接是否有效
@@ -76,6 +106,15 @@ func (p *ConnectionPool) GetMySQLClient(conn *models.DbConnection) (*MySQLClient
return client, nil
}
// GetMySQLPoolStats 获取 MySQL 连接池统计信息
func (p *ConnectionPool) GetMySQLPoolStats() *PoolStats {
if p.mysqlPool != nil {
stats := p.mysqlPool.Stats()
return &stats
}
return nil
}
// GetRedisClient 获取或创建 Redis 客户端
func (p *ConnectionPool) GetRedisClient(conn *models.DbConnection) (*RedisClient, error) {
p.mu.Lock()