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

Ade*_*ard 5 go redis redigo

使用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
    }
Run Code Online (Sandbox Code Playgroud)

我的问题是,每次我建立新连接时,都需要设置数据库,因为我在VPS上托管了许多站点,所以我使用不同的Redis数据库。

因此,如下所示:

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

conn.Do("SELECT", dbNumber)  //this is the call I want to avoid
Run Code Online (Sandbox Code Playgroud)

每次使用redis时都必须选择数据库,这似乎是多余的,并且也带来了一个问题,因为我将其用于会话,即,如果代码不是我的,则无法从池中使用redis连接来设置正确的db。它。

我想做的是为池设置dbno,以便每当有人从池中请求新连接时,它都已经设置了正确的db,即没有每次都明确设置它。

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

谢谢。

Liu*_*hui 8

您可以使用redis.DialOptionredis.DialDatabaseredis.DialPassword

conn, err := redis.Dial("tcp", "127.0.0.1:6379", redis.DialDatabase(1))
if err != nil {
    panic(err)
}
defer conn.Close()
Run Code Online (Sandbox Code Playgroud)


Sim*_*Fox 5

在拨号功能中选择数据库:

&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 {
            return nil, err
        }
        _, err := c.Do("SELECT", dbNum)
        if err != nil {
           c.Close()
           return nil, err
        }
        return c, nil
    }
Run Code Online (Sandbox Code Playgroud)

同样,从拨号而不是惊慌中返回错误。


Not*_*fer 2

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

  1. 提交一个补丁来自动执行此操作(python 库会执行此操作,但在保留状态时要小心)。

  2. 用您自己的自定义池包装您的 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,
                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()
    
    Run Code Online (Sandbox Code Playgroud)