This repository has been archived by the owner on Jul 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis_session_mgr.go
91 lines (74 loc) · 1.61 KB
/
redis_session_mgr.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
package session
import (
"sync"
"time"
"github.com/garyburd/redigo/redis"
uuid "github.com/satori/go.uuid"
)
type RedisSessionMgr struct {
addr string
passwd string
pool *redis.Pool
rwlock sync.RWMutex
sessionMap map[string]Session
}
func NewRedisSessionMgr() SessionMgr {
sr := &RedisSessionMgr{
sessionMap: make(map[string]Session, 1024),
}
return sr
}
//初始化一个pool
func newPool(server, password string) *redis.Pool {
return &redis.Pool{
MaxIdle: 64,
MaxActive: 1000,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", server)
if err != nil {
return nil, err
}
/*
if _, err := c.Do("AUTH", password); err != nil {
c.Close()
return nil, err
}*/
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Since(t) < time.Minute {
return nil
}
_, err := c.Do("PING")
return err
},
}
}
func (r *RedisSessionMgr) Init(addr string, options ...string) (err error) {
if len(options) > 0 {
r.passwd = options[0]
}
r.pool = newPool(addr, r.passwd)
r.addr = addr
return
}
func (r *RedisSessionMgr) CreateSession() (session Session, err error) {
r.rwlock.Lock()
defer r.rwlock.Unlock()
id := uuid.NewV4()
sessionId := id.String()
session = NewRedisSession(sessionId, r.pool)
r.sessionMap[sessionId] = session
return
}
func (r *RedisSessionMgr) Get(sessionId string) (session Session, err error) {
r.rwlock.RLock()
defer r.rwlock.RUnlock()
session, ok := r.sessionMap[sessionId]
if !ok {
err = ErrSessionNotExist
return
}
return
}