redis provider for session and cache support select db

This commit is contained in:
astaxie 2015-02-16 21:56:32 +08:00
parent 1b4158c15b
commit f988f035e5
2 changed files with 30 additions and 4 deletions

14
cache/redis/redis.go vendored
View File

@ -32,6 +32,7 @@ package redis
import (
"encoding/json"
"errors"
"strconv"
"time"
"github.com/garyburd/redigo/redis"
@ -48,6 +49,7 @@ var (
type RedisCache struct {
p *redis.Pool // redis connection pool
conninfo string
dbNum int
key string
}
@ -137,7 +139,7 @@ func (rc *RedisCache) ClearAll() error {
}
// start redis cache adapter.
// config is like {"key":"collection key","conn":"connection info"}
// config is like {"key":"collection key","conn":"connection info","dbNum":"0"}
// the cache item in redis are stored forever,
// so no gc operation.
func (rc *RedisCache) StartAndGC(config string) error {
@ -151,9 +153,12 @@ func (rc *RedisCache) StartAndGC(config string) error {
if _, ok := cf["conn"]; !ok {
return errors.New("config has no conn key")
}
if _, ok := cf["dbNum"]; !ok {
cf["dbNum"] = "0"
}
rc.key = cf["key"]
rc.conninfo = cf["conn"]
rc.dbNum, _ = strconv.Atoi(cf["dbNum"])
rc.connectInit()
c := rc.p.Get()
@ -166,6 +171,11 @@ func (rc *RedisCache) StartAndGC(config string) error {
func (rc *RedisCache) connectInit() {
dialFunc := func() (c redis.Conn, err error) {
c, err = redis.Dial("tcp", rc.conninfo)
_, selecterr := c.Do("SELECT", rc.dbNum)
if selecterr != nil {
c.Close()
return nil, selecterr
}
return
}
// initialize a new pool

View File

@ -118,12 +118,13 @@ type RedisProvider struct {
savePath string
poolsize int
password string
dbNum int
poollist *redis.Pool
}
// init redis session
// savepath like redis server addr,pool size,password
// e.g. 127.0.0.1:6379,100,astaxie
// savepath like redis server addr,pool size,password,dbnum
// e.g. 127.0.0.1:6379,100,astaxie,0
func (rp *RedisProvider) SessionInit(maxlifetime int64, savePath string) error {
rp.maxlifetime = maxlifetime
configs := strings.Split(savePath, ",")
@ -143,6 +144,16 @@ func (rp *RedisProvider) SessionInit(maxlifetime int64, savePath string) error {
if len(configs) > 2 {
rp.password = configs[2]
}
if len(configs) > 3 {
dbnum, err := strconv.Atoi(configs[1])
if err != nil || dbnum < 0 {
rp.dbNum = 0
} else {
rp.dbNum = dbnum
}
} else {
rp.dbNum = 0
}
rp.poollist = redis.NewPool(func() (redis.Conn, error) {
c, err := redis.Dial("tcp", rp.savePath)
if err != nil {
@ -154,6 +165,11 @@ func (rp *RedisProvider) SessionInit(maxlifetime int64, savePath string) error {
return nil, err
}
}
_, err = c.Do("SELECT", rp.dbNum)
if err != nil {
c.Close()
return nil, err
}
return c, err
}, rp.poolsize)