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条)

报告相同问题?

悬赏问题

  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 微信小游戏反编译后,出现找不到分包的情况
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题