Elon Musk (@elonmusk)
func (cm *ConfigManager) UpdateConfig(key string, value interface{}) error {
cm.mu.Lock()
defer cm.mu.Unlock()
// 验证配置键
if !lib.Contains(configKeys, key) {
return fmt.Errorf("invalid config key: %s", key)
}
// 转换值为字符串
var strValue string
switch v := value.(type) {
case string:
strValue = v
case float64:
strValue = fmt.Sprintf("%g", v)
case int:
strValue = fmt.Sprintf("%d", v)
default:
strValue = fmt.Sprintf("%v", v)
}
// 保存到 Redis
if err := cm.redis.Set(fmt.Sprintf("config:%s", key), strValue, 0); err != nil {
return err
}
// 更新版本号
cm.version = time.Now().Unix()
cm.redis.Set("config:version", fmt.Sprintf("%d", cm.version), 0)
// 更新本地配置
cm.configs[key] = strValue
cm.applyConfigs()
// 发布更新通知
cm.redis.Publish("config:update", fmt.Sprintf("%s:%s", key, strValue))
return nil
}