問題摘要:
此程式碼片段將文件中的資料載入到啟動期間的地圖。但是,在文件載入過程中遇到錯誤時會遇到問題。出現此問題的原因是程式碼在載入每個新檔案之前會清除地圖,如果發生錯誤且未保留先前的地圖狀態,可能會導致資料遺失。
建議的解決方案:
要克服這個問題,可以採用更直接的方法:
實作:
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