mapAppApi.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package dataStruct
  2. import (
  3. "MeterService/database/appApi"
  4. "strings"
  5. "sync"
  6. )
  7. type MapAppApi struct {
  8. RWLock sync.Mutex //sync.RWMutex
  9. Map *sync.Map
  10. TypeMap *sync.Map
  11. }
  12. var (
  13. once sync.Once
  14. appApiMap *MapAppApi
  15. )
  16. const (
  17. GetDevices = "GetDevices"
  18. SendCmd = "SendCmd"
  19. )
  20. func NewMapAppApi() *MapAppApi {
  21. once.Do(func() {
  22. appApiMap = &MapAppApi{
  23. Map: &sync.Map{},
  24. TypeMap: &sync.Map{},
  25. }
  26. appApiMap.TypeMap.Store(strings.ToLower(GetDevices), "")
  27. appApiMap.TypeMap.Store(strings.ToLower(SendCmd), "")
  28. })
  29. return appApiMap
  30. }
  31. func (m *MapAppApi) GetAppApiType() *sync.Map {
  32. return m.TypeMap
  33. }
  34. func (m *MapAppApi) GetAppApiTypeList() []string {
  35. array := make([]string, 0)
  36. m.TypeMap.Range(func(key, value interface{}) bool {
  37. array = append(array, key.(string))
  38. return true
  39. })
  40. return array
  41. }
  42. func (m *MapAppApi) IsAppApiExist(apiType string) bool {
  43. _, ok := m.TypeMap.Load(strings.ToLower(apiType))
  44. return ok
  45. }
  46. func (m *MapAppApi) Add(key string, val *appApi.AppApi) {
  47. m.RWLock.Lock()
  48. defer m.RWLock.Unlock()
  49. appMap, ok := m.Map.Load(strings.ToLower(key))
  50. if !ok {
  51. appMap = map[int]*appApi.AppApi{}
  52. }
  53. appMap.(map[int]*appApi.AppApi)[val.AppId] = val
  54. m.Map.Store(strings.ToLower(key), appMap)
  55. }
  56. func (m *MapAppApi) Get(key string) (map[int]*appApi.AppApi, bool) {
  57. m.RWLock.Lock()
  58. defer m.RWLock.Unlock()
  59. val, ok := m.Map.Load(strings.ToLower(key))
  60. if ok {
  61. return val.(map[int]*appApi.AppApi), true
  62. }
  63. return map[int]*appApi.AppApi{}, false
  64. }
  65. func (m *MapAppApi) RemoveAppId(appId int) {
  66. m.RWLock.Lock()
  67. defer m.RWLock.Unlock()
  68. m.Map.Range(func(key, value interface{}) bool {
  69. apiMap := value.(map[int]*appApi.AppApi)
  70. if apiMap[appId] != nil {
  71. delete(apiMap, appId)
  72. }
  73. return true
  74. })
  75. }
  76. func (m *MapAppApi) Remove(key string, val *appApi.AppApi) {
  77. m.RWLock.Lock()
  78. defer m.RWLock.Unlock()
  79. value, ok := m.Map.Load(strings.ToLower(key))
  80. if ok {
  81. apiMap := value.(map[int]*appApi.AppApi)
  82. if apiMap[val.AppId] != nil {
  83. delete(apiMap, val.AppId)
  84. }
  85. }
  86. m.Map.Store(key, value)
  87. }
  88. func (m *MapAppApi) RemoveAll(key string) {
  89. m.RWLock.Lock()
  90. defer m.RWLock.Unlock()
  91. m.Map.Delete(strings.ToLower(key))
  92. }