加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang:在Redigo的RedisPool上选择DB

发布时间:2020-12-16 09:27:42 所属栏目:大数据 来源:网络整理
导读:使用redigo,我创建了一个池,就像这样: 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 } 我遇
使用redigo,我创建了一个池,就像这样:

&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
    }

我遇到的问题是每次我得到一个新的连接,我需要设置数据库,因为我使用不同的数据库的redis,因为我在VPS上托管了许多站点.

所以,像这样:

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

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

每次我使用redis时都必须选择数据库似乎是多余的,并且因为我将它用于会话时也会出现问题,即我的代码不能与我的池中的redis连接一起工作,这使得设置正确的数据库“不可能”它.

我想要做的是为池设置dbno,以便每当有人要求从池中获得新连接时,它都会附带正确的数据库,即每次都没有明确设置它.

您是如何在应用程序中解决此问题的?

谢谢.

解决方法

如果这些库不支持它,那么你有两个选择:

>提交补丁以自动执行此操作(python lib执行此操作,但在保持状态时要小心).
>使用您自己的自定义池自定义您的redis池,例如(未经测试的代码,但您会得到这个想法):

// 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,// max number of connections
            Dial: func() (redis.Conn,error) {
            c,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()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读