Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: Selecting DB on a RedisPool in Redigo

Tags:

redis

go

redigo

using redigo, I create a pool, something like so:

&redis.Pool{
    MaxIdle:   80,
    MaxActive: 12000, // max number of connections
    Dial: func() (redis.Conn, error) {
        c, err := redis.Dial("tcp", host+":"+port)
        if err != nil {
            panic(err.Error())
        }
        return c, err
    }

the problem I have is that for each time I get a new connection, I need to set the db, as I use different db's of redis since I host a number of sites on the VPS.

So, something like this:

conn := pool.Get()
defer conn.Close()

conn.Do("SELECT", dbNumber)  //this is the call I want to avoid

Having to select the db each time I work with redis seems redundant and also poses a problem since I use it for sessions i.e. having code that is not mine working with my redis connection from my pool makes it "impossible" to set the correct db for it.

What I would like to do is to set the dbno for the pool so that whenever somebody asks for a new connection from the pool, it comes with the correct db already set i.e. not setting it explicitly each time.

How did you solve this in your applications?

Thanks.

like image 937
Adergaard Avatar asked Sep 07 '14 08:09

Adergaard


1 Answers

You can use redis.DialOption: redis.DialDatabase, redis.DialPassword

conn, err := redis.Dial("tcp", "127.0.0.1:6379", redis.DialDatabase(1))
if err != nil {
    panic(err)
}
defer conn.Close()
like image 135
Liu Zhihui Avatar answered Sep 20 '22 22:09

Liu Zhihui