Redigo Redis Pool真的应该是一个全局变量吗?

huangapple go评论71阅读模式
英文:

Is Redigo Redis Pool really supposed to be a global variable?

问题

在这个例子中Redigo文档中的Pool,Redis连接池被设置为main函数中的全局变量。这样做的方式是否合适?你真的应该随意使用全局变量吗?还是有更好、更推荐的方法来完成同样的事情?

英文:

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?

答案1

得分: 1

我看到的唯一其他解决方案是在"Passing Context to Interface Methods"中,例如:

创建一个接受嵌入式上下文和我们的handler类型的struct,通过ServeHTTP方法仍然满足http.Handler接口。

在你的情况下,这个struct将包括poolhandler函数。

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:    ...,
        // 其他数据
    }
}
英文:

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

huangapple
  • 本文由 发表于 2014年7月26日 21:47:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/24971669.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定