您的位置 首页 golang

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.Millise con d),
                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连接?


1000道程序员常见问题解析是最近新整理的一个专栏,欢迎大家提供问题与思路。

所有问题、思路、答案将整理在公众号,大家可以点击:关注,相互交流学习。

关注即可免费领取一份2020技术学习提升大礼包!(含文档、电子书、视频等等)

文章来源:智云一二三科技

文章标题:golang中redis连接池的问题

文章地址:https://www.zhihuclub.com/86683.shtml

关于作者: 智云科技

热门文章

网站地图