-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsessionmgr.go
92 lines (73 loc) · 1.53 KB
/
sessionmgr.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package fnet
import (
"sync"
"sync/atomic"
"github.com/fanjq99/glog"
)
type SessionManager struct {
sync.RWMutex
sessionMap map[int64]ISession
accID int64
}
const totalTryCount int = 100
func (sm *SessionManager) Add(session ISession) {
sm.Lock()
defer sm.Unlock()
var tryCount = totalTryCount
var id int64
for tryCount > 0 {
id = atomic.AddInt64(&sm.accID, 1)
glog.Info("Session add id", id)
if _, ok := sm.sessionMap[id]; !ok {
// 找到一个新的id
break
}
tryCount--
}
if tryCount == 0 {
glog.Errorln("sessionID override!", id)
}
session.SetID(id)
sm.sessionMap[id] = session
glog.Infof("Add Total connection: %d", len(sm.sessionMap))
}
func (sm *SessionManager) Remove(session ISession) {
sm.Lock()
defer sm.Unlock()
_, ok := sm.sessionMap[session.GetID()]
if ok {
delete(sm.sessionMap, session.GetID())
glog.Infof("Remove Total connection: %d", len(sm.sessionMap))
}
}
func (sm *SessionManager) Get(sid int64) ISession {
sm.RLock()
defer sm.RUnlock()
if v, ok := sm.sessionMap[sid]; ok {
return v
}
return nil
}
func (sm *SessionManager) CloseAll() {
tmp := make([]ISession, 0, sm.Len())
sm.Lock()
for _, v := range sm.sessionMap {
tmp = append(tmp, v)
}
sm.sessionMap = make(map[int64]ISession)
sm.Unlock()
for _, v := range tmp {
v.Close()
}
}
func (sm *SessionManager) Len() int {
sm.RLock()
defer sm.RUnlock()
return len(sm.sessionMap)
}
func NewSessionManager() *SessionManager {
return &SessionManager{
sessionMap: make(map[int64]ISession),
accID: 0,
}
}