このコードは、顧客構成のデータを保存する同時マップを管理します。サーバーの起動中に、特定のファイルからマップにデータがロードされます。また、新しいファイルを監視し、それらのファイルのデータでマップを更新し、古い状態をクリアします。
この問題は、読み取りメソッドでエラーが発生したときに発生します。この場合、以前の構成データを保持する必要があるにもかかわらず、マップ全体がクリアされ、空のままになります。
提案されたソリューションは、データ管理プロセスを簡素化します。
<code class="go">type CustomerConfig struct { Data map[string]bool // Add other properties if needed LoadedAt time.Time } func loadConfig() (*CustomerConfig, error) { cfg := &CustomerConfig{ Data: map[string]bool{}, LoadedAt: time.Now(), } // Implement the file loading logic here // If an error occurs, return it // If successful, return the config 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, fmt.Errorf("loading initial config failed: %w", err) } cc := &ConfigCache{ config: cfg, closeCh: make(chan struct{}), } // Launch goroutine to refresh config 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: // Implement the logic to detect changes changes := false 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 }</code>
<code class="go">// Initialize the cache cc, err := NewConfigCache() if err != nil { // Handle the error } // Get the current configuration when needed cfg := cc.GetConfig() // Remember to stop the cache manager when appropriate cc.Stop()</code>
このソリューションにより、以前の構成が失われる問題が防止され、構成更新の処理が簡素化されます。
以上が増分更新で同時顧客構成データを管理し、データ損失を回避するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。