package dataStruct import ( "MeterService/core/utils" "fmt" "sync" "time" ) type DMapClientState struct { RWLock sync.Mutex //sync.RWMutex Map *sync.Map } func NewDMapClientState() *DMapClientState { cm := &DMapClientState{ Map: new(sync.Map), } return cm } func (cm *DMapClientState) Add(key string, val *ClientState) { cm.Map.Store(key, val) } func (cm *DMapClientState) Remove(key string) { cm.Map.Delete(key) } func (cm *DMapClientState) Get(key string) (*ClientState, bool) { res := &ClientState{ Online: false, } x, ok := cm.Map.Load(key) if ok { res = x.(*ClientState) res.Online = true return res, true } return res, false } // AlterKey 修改key func (cm *DMapClientState) AlterKey(before, after string) bool { if before == after { return true } if v, ok := cm.Map.Load(before); !ok { return false } else { if _, ok = cm.Map.Load(after); ok { return false } val := v.(*ClientState) cm.Map.Store(after, val) cm.Map.Delete(before) return true } } func (cm *DMapClientState) Len() int { return 0 } func (cm *DMapClientState) Clean() { //cm.Map.Range(func(key, value any) bool { // cm.Map.Delete(key) // return true //}) cm.Map = new(sync.Map) } // UpdateTime 更新时间 func (cm *ClientState) UpdateTime() { cm.Times = time.Now().Unix() } /* ================================================== */ // HeartBeat 心跳检测 // 每遍历一次 查看所有sess 上次接收消息时间 如果超过 num 就删除该 sess func (cm *DMapClientState) HeartBeat(num int64) { for { time.Sleep(time.Second * 120) cm.Map.Range(func(k, v interface{}) bool { x := v.(*ClientState) if x.Online { if utils.ConnTimeoutJudge(x.Times) && x.FD.GetGRunFlag() { fmt.Println("HeartBeat Close...") x.FD.ExitClient() } } /*if vt.Online && time.Now().Unix()-vt.Times > num { if vt.FD.GetGRunFlag() { vt.FD.ExitClient() //CloseClient() } //this.Remove(i) //v.Online = false }*/ return true }) } }