Redigo Redis Pool是否应该是一个全球变量? [英] Is Redigo Redis Pool really supposed to be a global variable?

查看:173
本文介绍了Redigo Redis Pool是否应该是一个全球变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此示例中, Redigo Doc for Pool redis池是在func main中设置为全局变量。这是一个犹太人的方式来做事吗?如果你真的要左右使用全局变量,还是有更好的方法来完成同样的事情? 我见过唯一的其他解决方案,例如在将上下文传递给接口方法中:


创建一个接受嵌入式上下文和我们的处理函数的 struct type,并且感谢 ServeHTTP 。我们仍然满足 http.Handler 接口。


在你的情况下, struct 会包含 pool code>处理函数函数。

$ $ p $ type appContext struct {
池池


类型appHandler结构{
* appContext
h func(a * appContext,w http.ResponseWriter,r * http.Request) (int,error)
}

func(ah appHandler)ServeHTTP(w http.Respons eWriter,r * http.Request){
...
}


func main(){
context:=& appContext {
pool:...,
//任何其他数据
}
}


In the example here Redigo Docs for Pool the redis pool is set as a global variable in func main. Is that a kosher way to do things? Should you really be using global varibales left and right or is there a better, more preferred way of accomplishing the same thing?

解决方案

The only other solution have I seen, for instance in "Passing Context to Interface Methods" is:

create a struct that accepts an embedded context and our handler type, and we still satisfy the http.Handler interface thanks to ServeHTTP.

In your case, the struct would include the pool, and the handler function.

type appContext struct {
    pool Pool
}

type appHandler struct {
    *appContext
    h func(a *appContext, w http.ResponseWriter, r *http.Request) (int, error)
}

func (ah appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
   ...
}


func main() {
    context := &appContext{
        pool:    ...,
        // any other data
    }
}

这篇关于Redigo Redis Pool是否应该是一个全球变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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