英文:
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
我建议不要这样做,原因如下:
-
保持全局状态总是有风险的:它可能变得过时、损坏,总的来说,它会破坏隔离性和封装性。
-
由于AppEngine的工作方式,当你扩展或分布式部署时,你无法真正知道全局变量的全局范围,以及其他请求可能正在读取/写入它。
-
并发性。全局变量是并发性的祸根。为了保持理智,请不要在Web应用程序中使用全局变量。
英文:
I would suggest against it for the following reasons:
-
Keeping global state is always a hazard: it could go stale, corrupted and generally speaking it breaks isolation and encapsulation.
-
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.
-
Concurrency. Global variables are the bane of concurrency. Save yourselves your sanity and don't use global variables for a web app.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论