maps.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. package utils
  2. import (
  3. "sync"
  4. cmap "github.com/orcaman/concurrent-map"
  5. )
  6. type IMaps interface {
  7. Set(key string, val interface{})
  8. Get(key string) (interface{}, bool)
  9. Del(key string)
  10. }
  11. /**
  12. * 基础的Map结构
  13. *
  14. */
  15. type BaseMap struct {
  16. m map[string]interface{}
  17. }
  18. func (m *BaseMap) Set(key string, value interface{}) {
  19. m.m[key] = value
  20. }
  21. func (m *BaseMap) Get(key string) (interface{}, bool) {
  22. v, ok := m.m[key]
  23. return v, ok
  24. }
  25. func (m *BaseMap) Del(key string) {
  26. delete(m.m, key)
  27. }
  28. /**
  29. * CMap 并发结构
  30. *
  31. */
  32. type ConcurrentMap struct {
  33. m cmap.ConcurrentMap
  34. }
  35. func (m *ConcurrentMap) Set(key string, value interface{}) {
  36. m.m.Set(key, value)
  37. }
  38. func (m *ConcurrentMap) Get(key string) (interface{}, bool) {
  39. return m.m.Get(key)
  40. }
  41. func (m *ConcurrentMap) Del(key string) {
  42. m.m.Remove(key)
  43. }
  44. /**
  45. * Map 读写结构
  46. *
  47. */
  48. type RWLockMap struct {
  49. m map[string]interface{}
  50. lock sync.RWMutex
  51. }
  52. func (m *RWLockMap) Set(key string, value interface{}) {
  53. m.lock.Lock()
  54. defer m.lock.Unlock()
  55. m.m[key] = value
  56. }
  57. func (m *RWLockMap) Get(key string) (interface{}, bool) {
  58. m.lock.RLock()
  59. defer m.lock.RUnlock()
  60. v, ok := m.m[key]
  61. return v, ok
  62. }
  63. func (m *RWLockMap) Del(key string) {
  64. m.lock.Lock()
  65. defer m.lock.Unlock()
  66. delete(m.m, key)
  67. }
  68. /**
  69. * sync.Map 结构
  70. *
  71. */
  72. type SyncMap struct {
  73. m sync.Map
  74. }
  75. func (m *SyncMap) Set(key string, val interface{}) {
  76. m.m.Store(key, val)
  77. }
  78. func (m *SyncMap) Get(key string) (interface{}, bool) {
  79. return m.m.Load(key)
  80. }
  81. func (m *SyncMap) Del(key string) {
  82. m.m.Delete(key)
  83. }
  84. func NewMap(name string, len int) IMaps {
  85. switch name {
  86. case "cmap":
  87. return &ConcurrentMap{m: cmap.New()}
  88. case "rwmap":
  89. m := make(map[string]interface{}, len)
  90. return &RWLockMap{m: m}
  91. case "syncmap":
  92. return &SyncMap{}
  93. default:
  94. m := make(map[string]interface{}, len)
  95. return &BaseMap{m: m}
  96. }
  97. }