93 lines
1.8 KiB
Go
93 lines
1.8 KiB
Go
package session
|
|
|
|
import (
|
|
"errors"
|
|
"github.com/garyburd/redigo/redis"
|
|
uuid "github.com/satori/go.uuid"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type RedisSessionMgr struct {
|
|
//redis 地址
|
|
addr string
|
|
//密码
|
|
password string
|
|
//链接池
|
|
pool *redis.Pool
|
|
//锁
|
|
rwLock sync.RWMutex
|
|
//大map
|
|
sessionMap map[string]Session
|
|
}
|
|
|
|
//构造
|
|
|
|
func NewRedisSessionMgr() SessionMgr {
|
|
sr := &RedisSessionMgr{
|
|
sessionMap: make(map[string]Session, 32),
|
|
}
|
|
return sr
|
|
}
|
|
|
|
func (r *RedisSessionMgr) Init(addr string, options ...string) (err error) {
|
|
//若有其他参数
|
|
if len(options) > 0 {
|
|
r.password = options[0]
|
|
}
|
|
//创建链接池
|
|
r.pool = myPool(addr, r.password)
|
|
r.addr = addr
|
|
return
|
|
}
|
|
|
|
func myPool(addr, password string) *redis.Pool {
|
|
return &redis.Pool{
|
|
MaxIdle: 64,
|
|
IdleTimeout: 240 * time.Second,
|
|
MaxActive: 1000,
|
|
Dial: func() (redis.Conn, error) {
|
|
conn, err := redis.Dial("tcp", addr)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
//如果有密码,判断
|
|
if _, err = conn.Do("AUTH", password); err != nil {
|
|
conn.Close()
|
|
return nil, err
|
|
}
|
|
return conn, nil
|
|
|
|
},
|
|
//链接测试,开发时写
|
|
TestOnBorrow: func(c redis.Conn, t time.Time) error {
|
|
_, err := c.Do("PING")
|
|
return err
|
|
},
|
|
}
|
|
}
|
|
|
|
//mgr创建一个session
|
|
|
|
func (r *RedisSessionMgr) CreateSession() (session Session, err error) {
|
|
r.rwLock.Lock()
|
|
defer r.rwLock.Unlock()
|
|
//用uuid作为session id
|
|
sessionId := uuid.NewV4().String()
|
|
//创建一个session
|
|
redisSession := NewRedisSession(r.pool, sessionId)
|
|
r.sessionMap[sessionId] = redisSession
|
|
return
|
|
}
|
|
|
|
func (r *RedisSessionMgr) GetSession(sessionId string) (session Session, err error) {
|
|
r.rwLock.Lock()
|
|
defer r.rwLock.Unlock()
|
|
session, ok := r.sessionMap[sessionId]
|
|
if !ok {
|
|
err = errors.New("session not found")
|
|
return
|
|
}
|
|
return
|
|
}
|