memory_store.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package main
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. type tokenItem struct {
  7. Content []byte
  8. Timestamp int64
  9. }
  10. type MemoryStore struct {
  11. Map sync.Map
  12. Svr *TcpServer
  13. }
  14. func NewMemoryStore() *MemoryStore {
  15. ms := &MemoryStore{}
  16. ms.startRefresh()
  17. return ms
  18. }
  19. // 设置
  20. func (this* MemoryStore)Set(key string, bytess []byte) {
  21. this.Map.Store(key, &tokenItem{
  22. Content: bytess,
  23. Timestamp: time.Now().Unix(),
  24. })
  25. }
  26. // 移除
  27. func (this* MemoryStore)Remove(key string) {
  28. this.Map.Delete(key)
  29. }
  30. // 所有内容列表
  31. func (this *MemoryStore)All()map[string][]byte{
  32. mmap := make(map[string][]byte)
  33. this.Map.Range(func(k, v interface{})bool{
  34. ti := v.(*tokenItem)
  35. mmap[k.(string)] = ti.Content
  36. return true
  37. })
  38. return mmap
  39. }
  40. // 刷新
  41. func (this *MemoryStore)startRefresh(){
  42. go func() {
  43. // 两天检查一下
  44. ticket := time.NewTicker(time.Hour * 24 * 30)
  45. for {
  46. select {
  47. case <-ticket.C:
  48. keys := make([]string, 0)
  49. this.Map.Range(func(k, v interface{}) bool {
  50. item := v.(*tokenItem)
  51. if time.Now().Sub(time.Unix(item.Timestamp, 0)).Hours() > 24{
  52. // 大于两天
  53. keys = append(keys, k.(string))
  54. }
  55. return true
  56. })
  57. for i := range keys{
  58. if _, ok := this.Map.Load(keys[i]); ok{
  59. this.Svr.Broadcast("","remove", []byte(keys[i]))
  60. }
  61. this.Map.Delete(keys[i])
  62. }
  63. }
  64. }
  65. }()
  66. }