优化结构
This commit is contained in:
@@ -68,6 +68,13 @@ func (s *Store) Set(config Config) {
|
||||
config = cloneConfig(config)
|
||||
key := configKey(config.Kind, config.Provider)
|
||||
s.mu.Lock()
|
||||
if s.values == nil {
|
||||
s.values = make(map[string]Config)
|
||||
}
|
||||
if previous, exists := s.values[key]; exists && sameConfig(previous, config) {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.values[key] = config
|
||||
callbacks := s.matchingListenersLocked(config.Kind, config.Provider)
|
||||
s.mu.Unlock()
|
||||
@@ -83,7 +90,12 @@ func (s *Store) Delete(kind, provider string) {
|
||||
kind = strings.ToLower(strings.TrimSpace(kind))
|
||||
provider = strings.ToLower(strings.TrimSpace(provider))
|
||||
s.mu.Lock()
|
||||
delete(s.values, configKey(kind, provider))
|
||||
key := configKey(kind, provider)
|
||||
if _, exists := s.values[key]; !exists {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
delete(s.values, key)
|
||||
callbacks := s.matchingListenersLocked(kind, provider)
|
||||
s.mu.Unlock()
|
||||
config := Config{Kind: kind, Provider: provider}
|
||||
@@ -142,6 +154,9 @@ func (s *Store) Subscribe(kind, provider string, callback func(Config)) func() {
|
||||
s.mu.Lock()
|
||||
s.nextID++
|
||||
id := s.nextID
|
||||
if s.listeners == nil {
|
||||
s.listeners = make(map[uint64]listener)
|
||||
}
|
||||
s.listeners[id] = listener{kind: strings.ToLower(strings.TrimSpace(kind)), provider: strings.ToLower(strings.TrimSpace(provider)), callback: callback}
|
||||
s.mu.Unlock()
|
||||
return func() {
|
||||
|
||||
@@ -63,3 +63,23 @@ func TestStoreReplaceSkipsUnchangedValues(t *testing.T) {
|
||||
t.Fatal("changed replace notification was not delivered")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoreSetSkipsUnchangedValues(t *testing.T) {
|
||||
var store Store
|
||||
updates := make(chan Config, 1)
|
||||
stop := store.Subscribe("mq", "rabbitmq", func(config Config) { updates <- config })
|
||||
defer stop()
|
||||
config := Config{Kind: "mq", Provider: "rabbitmq", Enabled: true, Values: json.RawMessage(`{"host":"localhost"}`)}
|
||||
store.Set(config)
|
||||
select {
|
||||
case <-updates:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("initial set notification was not delivered")
|
||||
}
|
||||
store.Set(config)
|
||||
select {
|
||||
case update := <-updates:
|
||||
t.Fatalf("unchanged set emitted notification: %#v", update)
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user