mapClientState.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package dataStruct
  2. import (
  3. "MeterService/core/utils"
  4. "fmt"
  5. "sync"
  6. "time"
  7. )
  8. type DMapClientState struct {
  9. RWLock sync.Mutex //sync.RWMutex
  10. Map *sync.Map
  11. }
  12. func NewDMapClientState() *DMapClientState {
  13. cm := &DMapClientState{
  14. Map: new(sync.Map),
  15. }
  16. return cm
  17. }
  18. func (cm *DMapClientState) Add(key string, val *ClientState) {
  19. cm.Map.Store(key, val)
  20. }
  21. func (cm *DMapClientState) Remove(key string) {
  22. cm.Map.Delete(key)
  23. }
  24. func (cm *DMapClientState) Get(key string) (*ClientState, bool) {
  25. res := &ClientState{
  26. Online: false,
  27. }
  28. x, ok := cm.Map.Load(key)
  29. if ok {
  30. res = x.(*ClientState)
  31. res.Online = true
  32. return res, true
  33. }
  34. return res, false
  35. }
  36. // AlterKey 修改key
  37. func (cm *DMapClientState) AlterKey(before, after string) bool {
  38. if before == after {
  39. return true
  40. }
  41. if v, ok := cm.Map.Load(before); !ok {
  42. return false
  43. } else {
  44. if _, ok = cm.Map.Load(after); ok {
  45. return false
  46. }
  47. val := v.(*ClientState)
  48. cm.Map.Store(after, val)
  49. cm.Map.Delete(before)
  50. return true
  51. }
  52. }
  53. func (cm *DMapClientState) Len() int {
  54. return 0
  55. }
  56. func (cm *DMapClientState) Clean() {
  57. //cm.Map.Range(func(key, value any) bool {
  58. // cm.Map.Delete(key)
  59. // return true
  60. //})
  61. cm.Map = new(sync.Map)
  62. }
  63. // UpdateTime 更新时间
  64. func (cm *ClientState) UpdateTime() {
  65. cm.Times = time.Now().Unix()
  66. }
  67. /* ================================================== */
  68. // HeartBeat 心跳检测
  69. // 每遍历一次 查看所有sess 上次接收消息时间 如果超过 num 就删除该 sess
  70. func (cm *DMapClientState) HeartBeat(num int64) {
  71. for {
  72. time.Sleep(time.Second * 120)
  73. cm.Map.Range(func(k, v interface{}) bool {
  74. x := v.(*ClientState)
  75. if x.Online {
  76. if utils.ConnTimeoutJudge(x.Times) && x.FD.GetGRunFlag() {
  77. fmt.Println("HeartBeat Close...")
  78. x.FD.ExitClient()
  79. }
  80. }
  81. /*if vt.Online && time.Now().Unix()-vt.Times > num {
  82. if vt.FD.GetGRunFlag() {
  83. vt.FD.ExitClient() //CloseClient()
  84. }
  85. //this.Remove(i)
  86. //v.Online = false
  87. }*/
  88. return true
  89. })
  90. }
  91. }