我正在将Redigo与连接池一起使用。 下面是我的代码,用于设置连接池和对Redis的SET调用的包装器
//Create a pool of client connections to Redis
func newPool(MaxIdleConns int, Timeout int) *redis.Pool {
return &redis.Pool{
// Maximum number of idle connections in the pool.
MaxIdle: MaxIdleConns*10,
// Close connections after remaining idle for this duration
IdleTimeout: time.Duration(Timeout) * time.Second,
// Maximum number of connections allocated by the pool at a given time.
MaxActive: 500,
// If Wait is true and the pool is at the MaxActive limit, then Get() waits
// for a connection to be returned to the pool before returning.
Wait: true,
// Dial is an application supplied function for creating and
// configuring a connection.
Dial: func() (redis.Conn, error) {
// c, err := redis.DialTimeout("tcp", ":6379", 10*time.Second, 10*time.Second, 10*time.Second)
c, err := redis.Dial("tcp", ":6379")
if err != nil {
fmt.Println("Redis Pool Dial error: ", err)
}
return c, err
},
}
}
//SET Wrapper
func SET(p *redis.Pool, key string, value []byte) error {
c := p.Get()
defer c.Close()
_, err := c.Do("SET", key, value)
return err
}
上面的代码泄漏内存。
我正在defer c.Close()
中正确关闭连接。
令人惊讶的是,如果我像没有做任何_, err := c.Do("SET", key, value)
一样注释掉c.Do()
,那么程序不会泄漏内存。