redis操作
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.4 KiB

package redis
import (
"log"
"time"
redisdb "github.com/gomodule/redigo/redis"
)
// 定义redis链接池
var Pool *redisdb.Pool
var RedisServerUrl string = "127.0.0.1:6379"
// func init() {
// if Pool == nil {
// RedisInit()
// }
// }
func Conn(server_url ...string) {
var url string = RedisServerUrl
if len(server_url) > 0 {
url = server_url[0]
}
RedisInit(url)
}
// 初始化redis链接池
func RedisInit(serverUrl string, max ...int) {
var MaxActive, MaxIdle int
if len(max) > 0 {
MaxActive = max[0]
}
if len(max) > 1 {
MaxIdle = max[1]
}
if serverUrl != "" {
RedisServerUrl = serverUrl
}
Pool = &redisdb.Pool{
MaxIdle: MaxIdle, /*最大的空闲连接数*/
MaxActive: MaxActive, /*最大的激活连接数*/
Dial: redisConn,
}
}
func redisConn() (redisdb.Conn, error) {
dbOption := redisdb.DialDatabase(0)
pwOption := redisdb.DialPassword("")
// **重要** 设置读写超时
readTimeout := redisdb.DialReadTimeout(time.Second * time.Duration(2))
writeTimeout := redisdb.DialWriteTimeout(time.Second * time.Duration(5))
conTimeout := redisdb.DialConnectTimeout(time.Second * time.Duration(2))
c, err := redisdb.Dial("tcp", RedisServerUrl, dbOption, pwOption, readTimeout, writeTimeout, conTimeout)
if err != nil {
log.Println("redis connect failed", err)
return nil, err
} else {
log.Println("redis connected", RedisServerUrl)
}
return c, nil
}