/
session_manager.go
54 lines (46 loc) · 968 Bytes
/
session_manager.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
package kit
import (
"sync"
"time"
)
type SessionManager struct {
sync.RWMutex
pool map[string]*Session
}
func NewSessionManager() *SessionManager {
return &SessionManager{
pool: make(map[string]*Session),
}
}
func (m *SessionManager) GetSessionById(id string) *Session {
m.RLock()
defer m.RUnlock()
if session, ok := m.pool[id]; ok {
return session
}
return nil
}
func (m *SessionManager) createSession() *Session {
m.Lock()
defer m.Unlock()
session := newSession(m)
m.pool[session.Id] = session
return session
}
func (m *SessionManager) removeSession(s *Session) {
m.Lock()
delete(m.pool, s.Id)
m.Unlock()
}
func (m *SessionManager) CheckExpire() {
for {
// 20秒超时
expiredTime := time.Now().Add(-20 * time.Second)
for _, session := range m.pool {
if !session.LostConnection.IsZero() && session.LostConnection.Before(expiredTime) {
session.Close("lose connection and expired")
}
}
time.Sleep(time.Second)
}
}