douchu4048 2019-03-26 04:58
浏览 276

使用连接池时如何解决内存泄漏?

I am using redigo with connection pool. Below is my code for setting up connection pool and the wrapper for SET call to 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
}

The above code leaks memory. I am closing the connection properly in defer c.Close(). Surprisingly if I comment out _, err := c.Do("SET", key, value) as in I don't do any c.Do() then the program doesn't leak memory.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 关于#python#的问题:求帮写python代码
    • ¥20 MATLAB画图图形出现上下震荡的线条
    • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
    • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
    • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
    • ¥15 perl MISA分析p3_in脚本出错
    • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
    • ¥15 ubuntu虚拟机打包apk错误
    • ¥199 rust编程架构设计的方案 有偿
    • ¥15 回答4f系统的像差计算