首页 > 后端开发 > Golang > 正文

如何设计一个能够优雅地处理更新和错误的配置缓存?

Mary-Kate Olsen
发布: 2024-10-25 06:43:02
原创
723 人浏览过

How to Design a Configuration Cache That Handles Updates and Errors Gracefully?

从文件加载配置并使用新更新刷新

问题陈述:

代码设计涉及在启动时从文件加载配置并定期使用新版本刷新它。目标是建立一种处理以下要求的机制:

  • 对配置的并发访问
  • 重新加载检测到的配置更改
  • 对最新配置的可访问性
  • 更新期间立即访问最新配置
  • 更新失败时保留以前的配置

初始设计利用并发映射来存储配置,但面临更新过程中的错误可能导致地图为空的问题。

解决方案:

提出了一个简化的设计来满足所有要求:

CustomerConfig 结构:

定义要缓存的配置:

type CustomerConfig struct {
    Data map[string]bool
    LoadedAt time.Time
}
登录后复制

loadConfig 函数:

加载文件中的配置:

func loadConfig() (*CustomerConfig, error) {
    cfg := &CustomerConfig{
        Data:     map[string]bool{},
        LoadedAt: time.Now(),
    }

    // Logic to load files and populate cfg.Data
    // If an error occurs, return it

    // If loading succeeds, return the config
    return cfg, nil
}
登录后复制

ConfigCache 结构:

管理配置缓存:

type ConfigCache struct {
    configMu sync.RWMutex
    config   *CustomerConfig
    closeCh  chan struct{}
}
登录后复制

NewConfigCache 函数:

创建新的配置缓存:

func NewConfigCache() (*ConfigCache, error) {
    cfg, err := loadConfig()
    if err != nil {
        return nil, fmt.Errorf("loading initial config failed: %w", err)
    }

    cc := &ConfigCache{
        config:  cfg,
        closeCh: make(chan struct{}),
    }

    // Launch a goroutine to periodically check for changes and load new configs
    go cc.refresher()

    return cc, nil
}
登录后复制

刷新功能:

定期检查配置更改并更新缓存:

func (cc *ConfigCache) refresher() {
    ticker := time.NewTicker(1 * time.Minute) // Every minute
    defer ticker.Stop()

    for {
        select {
        case <-ticker.C:
            // Check for changes
            changes := false // Logic to detect changes
            if !changes {
                continue // No changes, continue
            }

            // Changes! Load new config:
            cfg, err := loadConfig()
            if err != nil {
                log.Printf("Failed to load config: %v", err)
                continue // Keep the previous config
            }

            // Apply / store new config
            cc.configMu.Lock()
            cc.config = cfg
            cc.configMu.Unlock()

        case <-cc.closeCh:
            return
        }
    }
}
登录后复制

停止函数:

停止复习 goroutine:

func (cc *ConfigCache) Stop() {
    close(cc.closeCh)
}
登录后复制

GetConfig 函数:

访问当前配置:

func (cc *ConfigCache) GetConfig() *CustomerConfig {
    cc.configMu.RLock()
    defer cc.configMu.RUnlock()
    return cc.config
}
登录后复制

用法:

cc, err := NewConfigCache()
if err != nil {
    // Handle the error appropriately
}

// Access the configuration whenever needed:
cfg := cc.GetConfig()
// Use the configuration here

// Stop the cache refreshing when necessary:
cc.Stop()
登录后复制

此解决方案确保:

  • 并发访问配置
  • 检测到更改时重新加载
  • 可访问最新配置
  • 更新期间可立即访问
  • 更新失败时保留以前的配置

以上是如何设计一个能够优雅地处理更新和错误的配置缓存?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!