dpe77294 2014-06-24 13:01
浏览 151

重新使用Redigo连接,而不是每次都重新创建它

Connecting to Redigo and manipulating data inside a function is easy like butter, but the problem comes when you have to re-use its connection, obviously for performance/practicality reasons.

Doing it inside a function like this works:

func main() {

    client, err := redis.Dial("tcp", ":6379")
    if err != nil {
        panic(err)
    }
    defer client.Close()

    client.Do("GET", "test:1")
}

But bringing it outside doesn't:

var Client = redis.Dial("tcp", ":6379")
defer Client.Close()

func main() {

        Client.Do("GET", "test:1")
    }

With the following error(s) returned:

./main.go:1: multiple-value redis.Dial() in single-value context
./main.go:2: non-declaration statement outside function body

I've tried putting the connection as a const(ant), putting defer inside the main function to my dismay not working too.

This is an even bigger concern as I have many other functions that have to communicate to Redis, but recreating the connection to Redis everytime seems silly.

The Redigo API just shows how to create a Dial instance but doesn't go further by explaining how to re-use it.

You may've been lost in my talk, but I wanted to put a bit of context here, so my clear and concise question is: How do you go about re-using (not recreating everytime) a Redigo connection?

  • 写回答

2条回答 默认 最新

  • dongzhi4690 2014-06-24 13:57
    关注

    The best way turned out to be using Pools, which are briefly documented here: Redigo Pools.

    A global variable won't eventually reuse a connection, so I ended up with something like this (using Pools as noted before):

    func newPool() *redis.Pool {
    return &redis.Pool{
                MaxIdle: 80,
                MaxActive: 12000, // max number of connections
                Dial: func() (redis.Conn, error) {
                        c, err := redis.Dial("tcp", ":6379")
                        if err != nil {
                                panic(err.Error())
                        }
                        return c, err
                },
        } 
    
    }
    
    var pool = newPool()
    
    func main() {
    
            c := pool.Get()
            defer c.Close()
    
            test,_:=c.Do("HGETALL", "test:1")
            fmt.Println(test)
    }
    

    If for example you want to reuse a pool inside another function you do it like this:

    func test() {
            c := pool.Get()
            defer c.Close()
    
            test2,_:=c.Do("HGETALL", "test:2")
            fmt.Println(test2)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。