goredispooldefer-keyword

Proper way to use redis pool in this scenario


I am currently using the redigo library for my project where i create a redis pool

I use defer to release the redis connection every time i get one from the pool

c := redisPool.Get()
defer c.Close()

But it will block forever in this scenario if MaxActive has been set

func function1() {
  c := redisPool.Get()
  defer c.Close()

  function2()

  ...

}

func function2() {
  c := redisPool.Get()
  defer c.Close()
  ...
}  

should i use only one redis connection in one goroutine?


Solution

  • You have a few options here.

    1. You can Close() when you are done, returning the connection to the pool and then calling function2. Upside: works, not too complex. Downside: management of returning the connection in the case of multiple exit points from the function.

    2. You can change function2 to take a redis.Conn argument that it uses and just pass that connection off. Upside: defer still works for function1. Downside: you need a connection to call function2 and need to do connection management from the calling site. In your example that is easy enough.

    3. Make sure you have at least N*2 max connections, where N is the max number of concurrent goroutines that will be running. Upside: Your code stays as-is without changes. Downside: limited in the number of concurrent calls to function1 you can make.