u
This commit is contained in:
1 parent
428d370874
commit
b408533fe7
15 files changed
+710
-97
No files matched your search
@@ -1,6 +1,7 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"base-framework/pkg/types"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"log"
|
||||
@@ -13,18 +14,6 @@ import (
|
||||
_ "github.com/lib/pq" // PostgreSQL 驱动,根据实际数据库替换
|
||||
)
|
||||
|
||||
// DBConfig 数据库配置结构体
|
||||
type DBConfig struct {
|
||||
Host string
|
||||
Port int
|
||||
Username string
|
||||
Password string
|
||||
Dbname string
|
||||
MaxOpenConns int // 最大打开连接数
|
||||
MaxIdleConns int // 最大空闲连接数
|
||||
ConnMaxLifetime time.Duration // 连接最大生命周期
|
||||
}
|
||||
|
||||
// 默认连接池参数
|
||||
const (
|
||||
defaultMaxOpenConns = 10
|
||||
@@ -33,7 +22,7 @@ const (
|
||||
)
|
||||
|
||||
var (
|
||||
dbConfigs map[string]DBConfig // 配置副本
|
||||
dbConfigs map[string]types.DBConfig // 配置副本
|
||||
dataSources = make(map[string]*sql.DB) // 连接池
|
||||
configsDSN = make(map[string]string) // key -> dsn
|
||||
mu sync.RWMutex
|
||||
@@ -83,7 +72,7 @@ func unmarshalConfigs() error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
temp := make(map[string]DBConfig)
|
||||
temp := make(map[string]types.DBConfig)
|
||||
if err := v.Unmarshal(&temp); err != nil {
|
||||
return fmt.Errorf("解析数据库配置失败: %w", err)
|
||||
}
|
||||
@@ -92,11 +81,11 @@ func unmarshalConfigs() error {
|
||||
}
|
||||
|
||||
// GetDBConfigs 并发安全地返回当前数据库配置副本
|
||||
func GetDBConfigs() map[string]DBConfig {
|
||||
func GetDBConfigs() map[string]types.DBConfig {
|
||||
mu.RLock()
|
||||
defer mu.RUnlock()
|
||||
|
||||
res := make(map[string]DBConfig, len(dbConfigs))
|
||||
res := make(map[string]types.DBConfig, len(dbConfigs))
|
||||
for k, v := range dbConfigs {
|
||||
res[k] = v
|
||||
}
|
||||
@@ -104,13 +93,13 @@ func GetDBConfigs() map[string]DBConfig {
|
||||
}
|
||||
|
||||
// buildDSN 构建 PostgreSQL DSN
|
||||
func buildDSN(cfg DBConfig) string {
|
||||
func buildDSN(cfg types.DBConfig) string {
|
||||
return fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
|
||||
cfg.Host, cfg.Port, cfg.Username, cfg.Password, cfg.Dbname)
|
||||
}
|
||||
|
||||
// ReloadDataSources 支持增量更新数据源,并验证数据库连接
|
||||
func ReloadDataSources(newConfigs map[string]DBConfig) error {
|
||||
func ReloadDataSources(newConfigs map[string]types.DBConfig) error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
@@ -171,7 +160,7 @@ func ReloadDataSources(newConfigs map[string]DBConfig) error {
|
||||
}
|
||||
|
||||
// applyDBConfig 设置 sql.DB 连接池参数,并应用默认值
|
||||
func applyDBConfig(db *sql.DB, cfg DBConfig) {
|
||||
func applyDBConfig(db *sql.DB, cfg types.DBConfig) {
|
||||
maxOpen := cfg.MaxOpenConns
|
||||
if maxOpen <= 0 {
|
||||
maxOpen = defaultMaxOpenConns
|
||||
|
||||
Reference in new issue
Block a user