package dataStruct import ( "MeterService/database/appApi" "strings" "sync" ) type MapAppApi struct { RWLock sync.Mutex //sync.RWMutex Map *sync.Map TypeMap *sync.Map } var ( once sync.Once appApiMap *MapAppApi ) const ( GetDevices = "GetDevices" SendCmd = "SendCmd" ) func NewMapAppApi() *MapAppApi { once.Do(func() { appApiMap = &MapAppApi{ Map: &sync.Map{}, TypeMap: &sync.Map{}, } appApiMap.TypeMap.Store(strings.ToLower(GetDevices), "") appApiMap.TypeMap.Store(strings.ToLower(SendCmd), "") }) return appApiMap } func (m *MapAppApi) GetAppApiType() *sync.Map { return m.TypeMap } func (m *MapAppApi) GetAppApiTypeList() []string { array := make([]string, 0) m.TypeMap.Range(func(key, value interface{}) bool { array = append(array, key.(string)) return true }) return array } func (m *MapAppApi) IsAppApiExist(apiType string) bool { _, ok := m.TypeMap.Load(strings.ToLower(apiType)) return ok } func (m *MapAppApi) Add(key string, val *appApi.AppApi) { m.RWLock.Lock() defer m.RWLock.Unlock() appMap, ok := m.Map.Load(strings.ToLower(key)) if !ok { appMap = map[int]*appApi.AppApi{} } appMap.(map[int]*appApi.AppApi)[val.AppId] = val m.Map.Store(strings.ToLower(key), appMap) } func (m *MapAppApi) Get(key string) (map[int]*appApi.AppApi, bool) { m.RWLock.Lock() defer m.RWLock.Unlock() val, ok := m.Map.Load(strings.ToLower(key)) if ok { return val.(map[int]*appApi.AppApi), true } return map[int]*appApi.AppApi{}, false } func (m *MapAppApi) RemoveAppId(appId int) { m.RWLock.Lock() defer m.RWLock.Unlock() m.Map.Range(func(key, value interface{}) bool { apiMap := value.(map[int]*appApi.AppApi) if apiMap[appId] != nil { delete(apiMap, appId) } return true }) } func (m *MapAppApi) Remove(key string, val *appApi.AppApi) { m.RWLock.Lock() defer m.RWLock.Unlock() value, ok := m.Map.Load(strings.ToLower(key)) if ok { apiMap := value.(map[int]*appApi.AppApi) if apiMap[val.AppId] != nil { delete(apiMap, val.AppId) } } m.Map.Store(key, value) } func (m *MapAppApi) RemoveAll(key string) { m.RWLock.Lock() defer m.RWLock.Unlock() m.Map.Delete(strings.ToLower(key)) }