문제 개요:
이 코드 조각은 파일의 데이터를 시작하는 동안 지도. 그러나 파일을 로드하는 동안 오류가 발생하면 문제가 발생합니다. 이 문제는 코드가 각각의 새 파일을 로드하기 전에 지도를 지우기 때문에 발생합니다. 이로 인해 오류가 발생하고 이전 지도 상태가 유지되지 않으면 데이터 손실이 발생할 수 있습니다.
제안된 솔루션:
이 문제를 극복하기 위해 보다 간단한 접근 방식을 채택할 수 있습니다.
구현:
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