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?
You have a few options here.
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.
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.
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.
You can use following approach to make sure application won't lock/ break.
wait: true
in the pool configuration.// 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.
maxclient
limit is larger than MaxActive
The default maxclient
is 10k.Most applications can keep connection use low by avoiding long or blocking operations (other than calls to Redis) between the call to Get() and the call to Close().
Hope this helps.