package iotMap import ( iotStruct "IotAdmin/iot/struct" "sync" ) type DtuClientMap struct { RWLock sync.Mutex //sync.RWMutex Map *sync.Map } func NewDtuClientMap() *DtuClientMap { cm := &DtuClientMap{ Map: new(sync.Map), } return cm } func (cm *DtuClientMap) Add(key string, val *iotStruct.DtuClient) { cm.Map.Store(key, val) } func (cm *DtuClientMap) Remove(key string) { cm.Map.Delete(key) } func (cm *DtuClientMap) Get(key string) (*iotStruct.DtuClient, bool) { res := &iotStruct.DtuClient{ Online: false, } x, ok := cm.Map.Load(key) if ok { res = x.(*iotStruct.DtuClient) res.Online = true return res, true } return res, false } // AlterKey 修改key func (cm *DtuClientMap) AlterKey(before, after string) bool { if before == after { return true } if v, ok := cm.Map.Load(before); !ok { return false } else { if _, ok = cm.Map.Load(after); ok { return false } val := v.(*iotStruct.DtuClient) cm.Map.Store(after, val) cm.Map.Delete(before) return true } } func (cm *DtuClientMap) Len() int { c := 0 cm.Map.Range(func(key, value interface{}) bool { c++ return true }) return c } func (cm *DtuClientMap) Clean() { cm.Map = new(sync.Map) }