dongxie3352 2014-09-07 08:09
浏览 465
已采纳

Golang:在Redigo中的RedisPool上选择数据库

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.

  • 写回答

4条回答 默认 最新

  • 普通网友 2014-09-07 08:54
    关注

    If these libs don't support it, then you have two options:

    1. submit a patch to automate this (the python lib does that, but be careful when keeping the state).

    2. Wrap your redis pool with your own custom pool that automates this, something like (untested code, but you'll get the idea):

          // a pool embedding the original pool and adding adbno state
          type DbnoPool struct {
             redis.Pool
             dbno int
          }
      
      
          // "overriding" the Get method
          func (p *DbnoPool)Get() Connection {
             conn := p.Pool.Get()
             conn.Do("SELECT", p.dbno)
             return conn
          }
      
          pool := &DbnoPool {
              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
              },
              3, // the db number
          }
      
          //now you call it normally
          conn := pool.Get()
          defer conn.Close()
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!