我们应该将App Engine上下文存储在全局变量中,还是在每个请求中创建它?

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

Should we store App Engine Context in a global var versus creating it for every request?

问题

我们目前在每个请求上生成App Engine上下文。我们在其他地方读到过,这并不重要,因为App Engine本质上会缓存上下文。

func addHandler(res http.ResponseWriter, req *http.Request) {
    c := appengine.NewContext(req)
}

我们的问题是:将App Engine上下文存储在全局变量中是否有意义?

英文:

We currently generate the App Engine context on every single request. We've read elsewhere, that this doesn't matter as App Engine essentially caches the context anyway.

func addHandler(res http.ResponseWriter, req *http.Request) {
	c := appengine.NewContext(req)

Our question: Would it make any sense to store the App Engine context in a global variable?

答案1

得分: 3

我建议不要这样做,原因如下:

  1. 保持全局状态总是有风险的:它可能变得过时、损坏,总的来说,它会破坏隔离性和封装性。

  2. 由于AppEngine的工作方式,当你扩展或分布式部署时,你无法真正知道全局变量的全局范围,以及其他请求可能正在读取/写入它。

  3. 并发性。全局变量是并发性的祸根。为了保持理智,请不要在Web应用程序中使用全局变量。

英文:

I would suggest against it for the following reasons:

  1. Keeping global state is always a hazard: it could go stale, corrupted and generally speaking it breaks isolation and encapsulation.

  2. Due to the way AppEngine works as you scale up or out, you don't how truly global that global really is and what other requests might be reading/writing to it.

  3. Concurrency. Global variables are the bane of concurrency. Save yourselves your sanity and don't use global variables for a web app.

huangapple
  • 本文由 发表于 2014年2月18日 23:33:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/21858296.html
匿名

发表评论

匿名网友

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

确定