dongzj2015 2015-05-14 17:54
浏览 9

跨路线共享Redis设置

I have a number of routes in my routes.go file and they all call my redis database. I'm wondering how I can avoid calling the dial and AUTH calls in every route.

I've tried setting variables outside the functions like this:

var (
  c, err = redis.Dial("tcp", ADDRESS)
  _, err = c.Do("AUTH", "testing")
)

but then the compiler doesn't like err being used twice.

  • 写回答

2条回答 默认 最新

  • dpl9717 2015-05-14 18:32
    关注

    First, only use var for declaring variables. You can't run code outside of functions, so there's no use in trying to create connections inside a var statement. Use init() if you need something run at startup.

    The redis connections can't be used with concurrent requests. If you want to share a redis connection across multiple routes, you need to have a safe method for concurrent use. In the case of github.com/garyburd/redigo/redis you want to use a Pool. You can do the AUTH call inside the Dial function, returning a ready connection each time.

    var redisPool *redis.Pool
    
    func init() {
        redisPool = &redis.Pool{
            MaxIdle:     3,
            IdleTimeout: 240 * time.Second,
            Dial: func() (redis.Conn, error) {
                c, err := redis.Dial("tcp", server)
                if err != nil {
                    return nil, err
                }
                if _, err := c.Do("AUTH", password); err != nil {
                    c.Close()
                    return nil, err
                }
                return c, err
            },
        }
    }
    

    Then each time you need a connection, you get one from the pool, and return it when you're done.

    conn := redisPool.Get()
    // conn.Close() just returns the connection to the pool
    defer conn.Close()
    
    if err := conn.Err(); err != nil {
        // conn.Err() will have connection or Dial related errors
        return nil, err
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大