问题概要:
此代码片段将文件中的数据加载到启动期间的地图。但是,在文件加载过程中遇到错误时会遇到问题。出现此问题的原因是代码在加载每个新文件之前会清除地图,如果发生错误且未保留先前的地图状态,可能会导致数据丢失。
建议的解决方案:
要克服这个问题,可以采用更直接的方法:
实现:
type CustomerConfig struct {
Data map[string]bool
LoadedAt time.Time
}
func loadConfig() (*CustomerConfig, error) {
cfg := &CustomerConfig{
Data: map[string]bool{},
LoadedAt: time.Now(),
}
// Load files and populate cfg.Data
// Return error if encountered
return cfg, nil
}
type ConfigCache struct {
configMu sync.RWMutex
config *CustomerConfig
closeCh chan struct{}
}
func NewConfigCache() (*ConfigCache, error) {
cfg, err := loadConfig()
if err != nil {
return nil, err
}
cc := &ConfigCache{
config: cfg,
closeCh: make(chan struct{}),
}
go cc.refresher()
return cc, nil
}
func (cc *ConfigCache) refresher() {
ticker := time.NewTicker(1 * time.Minute)
defer ticker.Stop()
for {
select {
case <-ticker.C:
// Check for changes
changes := false // Implement logic to detect changes
if !changes {
continue
}
cfg, err := loadConfig()
if err != nil {
log.Printf("Failed to load config: %v", err)
continue
}
cc.configMu.Lock()
cc.config = cfg
cc.configMu.Unlock()
case <-cc.closeCh:
return
}
}
}
func (cc *ConfigCache) Stop() {
close(cc.closeCh)
}
func (cc *ConfigCache) GetConfig() *CustomerConfig {
cc.configMu.RLock()
defer cc.configMu.RUnlock()
return cc.config
}
用法:
cc, err := NewConfigCache()
if err != nil {
// Handle error
}
cfg := cc.GetConfig() // Access the latest configuration
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3