Как исправить утечку памяти при использовании пула соединений? - PullRequest
2 голосов
/ 26 марта 2019

Я использую redigo с пулом соединений.Ниже приведен мой код для настройки пула соединений и оболочки для вызова SET для Redis

//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(), тогда программа не утечет память.

...