This commit is contained in:
oneao committed 2025-08-13 17:30:57 +08:00
1 parent 7552670e4a
commit 01ea998605
13 files changed
+173 -45

No files matched your search

@@ -109,7 +109,7 @@ func buildDSN(cfg DBConfig) string {
cfg.Host, cfg.Port, cfg.Username, cfg.Password, cfg.Dbname)
}
// ReloadDataSources 支持增量更新数据源
// ReloadDataSources 支持增量更新数据源,并验证数据库连接
func ReloadDataSources(newConfigs map[string]DBConfig) error {
mu.Lock()
defer mu.Unlock()
@@ -120,30 +120,39 @@ func ReloadDataSources(newConfigs map[string]DBConfig) error {
newDSN := buildDSN(cfg)
oldDSN, exists := configsDSN[key]
if !exists {
// 新增数据源或配置变更
if !exists || oldDSN != newDSN {
// 关闭旧连接(如果存在)
if exists {
if oldDB := dataSources[key]; oldDB != nil {
_ = oldDB.Close()
}
}
db, err := sql.Open("postgres", newDSN)
if err != nil {
log.Printf("[db] 新增数据源 %s 失败: %v", key, err)
log.Printf("[db] 数据源 %s Open 失败: %v", key, err)
continue
}
// 尝试实际连接数据库
if err := db.Ping(); err != nil {
log.Printf("[db] 数据源 %s 连接失败: %v", key, err)
_ = db.Close()
continue
}
applyDBConfig(db, cfg)
dataSources[key] = db
configsDSN[key] = newDSN
log.Printf("[db] 新增数据源 %s 成功", key)
} else if oldDSN != newDSN {
if oldDB := dataSources[key]; oldDB != nil {
_ = oldDB.Close()
if !exists {
log.Printf("[db] 新增数据源 %s 成功", key)
} else {
log.Printf("[db] 更新数据源 %s 成功", key)
}
db, err := sql.Open("postgres", newDSN)
if err != nil {
log.Printf("[db] 更新数据源 %s 失败: %v", key, err)
continue
}
applyDBConfig(db, cfg)
dataSources[key] = db
configsDSN[key] = newDSN
log.Printf("[db] 更新数据源 %s 成功", key)
}
// 配置没变,不用操作
retain[key] = true
}