forked from davyxu/cellnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsesmgr.go
86 lines (57 loc) · 1.34 KB
/
sesmgr.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
package cellnet
import (
"sync"
"sync/atomic"
)
// 完整功能的会话管理
type SessionManager interface {
SessionAccessor
Add(Session)
Remove(Session)
Count() int
}
type sesMgr struct {
sesById sync.Map // 使用Id关联会话
sesIDGen int64 // 记录已经生成的会话ID流水号
count int64 // 记录当前在使用的会话数量
}
func (self *sesMgr) Count() int {
return int(atomic.LoadInt64(&self.count))
}
func (self *sesMgr) Add(ses Session) {
id := atomic.AddInt64(&self.sesIDGen, 1)
self.count = atomic.AddInt64(&self.count, 1)
ses.(interface {
SetID(int64)
}).SetID(id)
self.sesById.Store(id, ses)
}
func (self *sesMgr) Remove(ses Session) {
self.sesById.Delete(ses.ID())
self.count = atomic.AddInt64(&self.count, -1)
}
// 获得一个连接
func (self *sesMgr) GetSession(id int64) Session {
if v, ok := self.sesById.Load(id); ok {
return v.(Session)
}
return nil
}
func (self *sesMgr) VisitSession(callback func(Session) bool) {
self.sesById.Range(func(key, value interface{}) bool {
return callback(value.(Session))
})
}
func (self *sesMgr) CloseAllSession() {
self.VisitSession(func(ses Session) bool {
ses.Close()
return true
})
}
func (self *sesMgr) SessionCount() int {
v := atomic.LoadInt64(&self.count)
return int(v)
}
func NewSessionManager() SessionManager {
return &sesMgr{}
}