golang中的redigo
原创
©著作权归作者所有:来自51CTO博客作者盼盼编程的原创作品,请联系作者获取转载授权,否则将追究法律责任
安装
go get -u github.com/gomodule/redigo/redis
连接
var (
redisHost = "127.0.0.1:6379"
redisPass = "root"
)
//创建redis连接池
func newRedisPool() *redis.Pool {
return &redis.Pool{
MaxIdle: 50,
MaxActive: 30,
IdleTimeout: 300 * time.Second,
Dial: func()(redis.Conn, error) {
//1. 打开连接
conn, err := redis.Dial("tcp", redisHost)
if err != nil {
fmt.Println(err)
return nil, err
}
//2. 访问认证
if _, err = conn.Do("AUTH", redisPass); err != nil {
conn.Close()
return nil, err
}
return conn, nil
},
//=定时检查连接有没有效
TestOnBorrow: func(conn redis.Conn, t time.Time) error {
if time.Since(t) < time.Minute {
return nil
}
_, err := conn.Do("PING")
return err
},
}
}
func RedisPool() *redis.Pool {
return newRedisPool()
}
func main() {
//获得redis连接
rConn := RedisPool().Get()
defer rConn.Close()
}