diff --git a/config/config.go b/config/config.go index 15bf20b..a66271e 100644 --- a/config/config.go +++ b/config/config.go @@ -18,6 +18,7 @@ var ( mu sync.RWMutex aiBalancer *AIBalancer + balancerMu sync.RWMutex ) type Config struct { @@ -332,7 +333,16 @@ func (b *AIBalancer) Next() (*AIConfig, error) { return &highPriorityAIs[0], nil } -// 添加获取 AIBalancer 的方法 +// ResetAIBalancer 重置 AI 负载均衡器 +func ResetAIBalancer(ais []AIConfig) { + balancerMu.Lock() + defer balancerMu.Unlock() + aiBalancer = NewAIBalancer(ais) +} + +// GetAIBalancer 获取当前的 AI 负载均衡器 func GetAIBalancer() *AIBalancer { + balancerMu.RLock() + defer balancerMu.RUnlock() return aiBalancer } diff --git a/handlers/config.go b/handlers/config.go index 879f232..825ac7f 100644 --- a/handlers/config.go +++ b/handlers/config.go @@ -135,8 +135,13 @@ func (h *ConfigHandler) UpdateConfig(c *gin.Context) { return } - log.Printf("配置更新成功") + // 更新运行时配置 h.cfg = &newConfig + + // 重新初始化 AI 负载均衡器 + config.ResetAIBalancer(newConfig.AIs) + + log.Printf("配置更新成功") c.JSON(http.StatusOK, gin.H{"message": "配置更新成功"}) } diff --git a/main.go b/main.go index 6998649..0a0395f 100644 --- a/main.go +++ b/main.go @@ -6,8 +6,9 @@ import ( "code-review/services" "code-review/services/ai" "fmt" - "github.com/gin-gonic/gin" "log" + + "github.com/gin-gonic/gin" ) func main() { @@ -22,10 +23,10 @@ func main() { } // 初始化 AI 负载均衡器 - aiBalancer := config.NewAIBalancer(cfg.AIs) + config.ResetAIBalancer(cfg.AIs) // 获取一个 AI 配置 - aiConfig, err := aiBalancer.Next() + aiConfig, err := config.GetAIBalancer().Next() if err != nil { log.Fatalf("获取 AI 配置失败: %v", err) }