cachelist.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. package dbserver
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. //实现一个缓存存列表
  7. //可以添加、删除元素、不存在时添加
  8. //添加:列表中不存在时添加,存在时替换
  9. //删除列表:按照添加时的顺序删除元素
  10. type saveItem struct {
  11. val interface{}
  12. tick int64
  13. }
  14. type CacheSaveList struct {
  15. sync.Mutex
  16. allItem map[string]*saveItem
  17. orderItem []string
  18. pool sync.Pool
  19. }
  20. func NewCacheList() *CacheSaveList {
  21. l := new(CacheSaveList)
  22. l.orderItem = make([]string, 0)
  23. l.allItem = make(map[string]*saveItem)
  24. l.pool.New = func() interface{} {
  25. return new(saveItem)
  26. }
  27. return l
  28. }
  29. func (l *CacheSaveList) newSaveItem(val interface{}) *saveItem {
  30. it := l.pool.Get()
  31. it1 := it.(*saveItem)
  32. it1.val = val
  33. it1.tick = time.Now().Unix()
  34. return it1
  35. }
  36. func (l *CacheSaveList) Add(key string, val interface{}) int {
  37. l.Lock()
  38. defer l.Unlock()
  39. if v, ok := l.allItem[key]; !ok {
  40. l.orderItem = append(l.orderItem, key)
  41. it1 := l.newSaveItem(val)
  42. l.allItem[key] = it1
  43. } else {
  44. v.val = val
  45. }
  46. return len(l.orderItem)
  47. }
  48. //列表中不存在时添加,
  49. func (l *CacheSaveList) Addnx(key string, val interface{}) {
  50. l.Lock()
  51. defer l.Unlock()
  52. if _, ok := l.allItem[key]; !ok {
  53. l.orderItem = append(l.orderItem, key)
  54. it1 := l.newSaveItem(val)
  55. l.allItem[key] = it1
  56. }
  57. }
  58. func (l *CacheSaveList) Pop() interface{} {
  59. l.Lock()
  60. defer l.Unlock()
  61. if len(l.orderItem) == 0 {
  62. // if len(l.allItem) > 0 {
  63. // l.allItem = make(map[int64]interface{})
  64. // }
  65. return nil
  66. }
  67. k := l.orderItem[0]
  68. l.orderItem = l.orderItem[1:]
  69. if v, ok := l.allItem[k]; ok {
  70. delete(l.allItem, k)
  71. v2 := v.val
  72. v.val = nil
  73. l.pool.Put(v)
  74. return v2
  75. }
  76. return nil
  77. }
  78. func (l *CacheSaveList) GetHeadTick() int64 {
  79. l.Lock()
  80. defer l.Unlock()
  81. if len(l.orderItem) == 0 {
  82. return 0
  83. }
  84. k := l.orderItem[0]
  85. if v, ok := l.allItem[k]; ok {
  86. return v.tick
  87. }
  88. //不应该会执行到这里
  89. l.orderItem = l.orderItem[1:]
  90. return 0
  91. }
  92. func (l *CacheSaveList) Count() int {
  93. return len(l.orderItem)
  94. }
  95. //缓存读列表
  96. //可以添加、删除、查找元素、超时删除
  97. //查找:存在时返回值,不存在时返回空;
  98. //超时删除:添加的元素,保存一段时间后删除
  99. //添加:加入列表,设置时间戳