3

我正在使用 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()那么程序就不会泄漏内存。

4

0 回答 0