github.com/aaabigfish/gopkg@v1.1.0/etcdv3/cache.go (about) 1 package etcdv3 2 3 import "sync" 4 5 type Cache struct { 6 mtx sync.RWMutex 7 Instances []*KvEntry 8 } 9 10 func (c *Cache) UpdateByKvPair(kv []*KvEntry) { 11 c.mtx.Lock() 12 defer c.mtx.Unlock() 13 14 c.Instances = nil 15 c.Instances = make([]*KvEntry, len(kv)) 16 for i, v := range kv { 17 c.Instances[i] = &KvEntry{ 18 Key: v.Key, 19 Value: v.Value, 20 } 21 } 22 } 23 24 func (c *Cache) UpdateByWatchEvent(wev []*WatchEvent) { 25 c.mtx.Lock() 26 defer c.mtx.Unlock() 27 28 for _, e := range wev { 29 if e.OpType == 0 { 30 kv, _ := c.GetKvEntry(e) 31 if kv == nil { 32 c.Instances = append(c.Instances, e.Kv) 33 } else { 34 kv.Value = e.Kv.Value 35 } 36 } else { 37 _, i := c.GetKvEntry(e) 38 if i == 0 && len(c.Instances) == 1 { 39 c.Instances = nil 40 } else { 41 c.Instances = append(c.Instances[:i], c.Instances[i+1:]...) 42 } 43 } 44 } 45 } 46 47 func (c *Cache) GetKvEntry(ev *WatchEvent) (*KvEntry, int) { 48 for i, o := range c.Instances { 49 if o.Key == ev.Kv.Key { 50 return c.Instances[i], i 51 } 52 } 53 return nil, -1 54 }