跨路线共享Redis设置 [英] Sharing Redis settings across routes

查看:99
本文介绍了跨路线共享Redis设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 routes.go 文件中有许多路由,它们都会调用我的redis数据库。我想知道如何避免在每个路由中调用拨号 AUTH 呼叫。



我试过在这样的函数之外设置变量:

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

但编译器不会像 err 被使用两次。

解决方案

首先,仅使用var来声明变量。你不能在函数之外运行代码,所以在var语句中尝试创建连接是没有用的。如果你需要在启动时运行,使用 init()

redis连接不能用于并发要求。如果你想跨多个路由共享一个redis连接,你需要一个安全的并发使用方法。在 github.com/garyburd/redigo/redis 的情况下,您希望使用。您可以在Dial函数中执行 AUTH 调用,每次都返回一个就绪连接。

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

然后每次您需要连接时,您都会从池中获得一个,并在您返回时返回'

  conn:= redisPool.Get()
// conn.Close()只返回连接池
推迟conn.Close()

如果err:= conn.Err(); err!= nil {
// conn.Err()将连接或拨号相关的错误
返回nil,err
}


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.

解决方案

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
}

这篇关于跨路线共享Redis设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆