golang中redis连接池的问题

redis连接池的疑问,代码如下

package utils

import (
    red "github.com/gomodule/redigo/redis"
    "time"
    "fmt"
)

type Redis struct {
    pool     *red.Pool
}

var redis *Redis

func initRedis() {
    redis = new(Redis)
    redis.pool = &red.Pool{
        MaxIdle:     256,
        MaxActive:   0,
        IdleTimeout: time.Duration(120),
        Dial: func() (red.Conn, error) {
            return red.Dial(
                "tcp",
                "127.0.0.1:6379",
                red.DialReadTimeout(time.Duration(1000)*time.Millisecond),
                red.DialWriteTimeout(time.Duration(1000)*time.Millisecond),
                red.DialConnectTimeout(time.Duration(1000)*time.Millisecond),
                red.DialDatabase(0),
                //red.DialPassword(""),
            )
        },
    }
}

func Exec(cmd string, key interface{}, args ...interface{}) (interface{}, error) {
    con := redis.pool.Get()
    if err := con.Err(); err != nil {
        return nil, err
    }
    defer con.Close()
    parmas := make([]interface{}, 0)
    parmas = append(parmas, key)

    if len(args) > 0 {
        for _, v := range args {
            parmas = append(parmas, v)
        }
    }
    return con.Do(cmd, parmas...)
}

func main() {
    initRedis()
    Exec("set","hello","world")
    fmt.Print(2)
    result,err := Exec("get","hello")
    if err != nil {
        fmt.Print(err.Error())
    }
    str,_:=red.String(result,err)
    fmt.Print(str)
}

这样操作后,每次调用initRedis()是不是相当于重新执行了一次redis连接?

阅读 5k
3 个回答

不会,initRedis()只是初始化Pool对象,多次调用只会重新初始化redis对象,原有的会被gc回收。实际连接是在pool.Get做的。

func (p *Pool) Get() Conn {
    pc, err := p.get(nil)
    if err != nil {
        return errorConn{err}
    }
    return &activeConn{p: p, pc: pc}
}

// get prunes stale connections and returns a connection from the idle list or
// creates a new connection.
func (p *Pool) get(ctx context.Context) (*poolConn, error) {
    // ...
    c, err := p.dial(ctx)
    // ...
}

应该是的,你的redis重新=new(Redis),可以在上面做判断if redis == nil { return} 掉

但也可能会触发gc,把原连接给清掉?

只是初始化连接池,gc释放没那么快,当释放的时候,还会占用tcp连接的。一般都是提前初始化好全局的连接池。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题