为什么在 play 2.5 中使用单例控制器? [英] Why use singleton controllers in play 2.5?

查看:20
本文介绍了为什么在 play 2.5 中使用单例控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始,我认为我不太了解它.据我所知,所有控制器都是在创建路由器的那一刻作为依赖项创建的.然后它们会一直存在,直到应用程序终止时路由器死亡.如果是这种情况,将它们声明为单例似乎是多余的.

I'm just starting out and I dont think i understand it very well. From what I understand all controllers are created as dependencies the moment the router is created. They then live on until the router dies when the application terminates. If this is the case declaring them as singletons seem redundant.

推荐答案

为了摆脱全局状态(这与无状态设计的想法背道而驰)Play 引入了 DI(我认为是 v2.4 左右)和 v2.5它现在默认使用注入的路由器.Google Guice 是 Play 打包的默认 DI 框架(你可以使用其他的,但 Guice 是默认的).

To get rid of global state (which goes against the idea of a stateless design) Play introduced DI (I think around v2.4) and in v2.5 it now uses an injected router by default. Google Guice is the default DI framework packaged by Play (you can use others but Guice is the default).

现在(一般而言)Guice 认为创建控制器的新实例比使用单例更快,线程更安全 - 请参阅 Guice 文档了解更多.

Now (in general) Guice takes the view that creating new instances of a Controller is faster, and more thread safe than using a singleton - see the Guice docs for more.

如果您需要将控制器实例限制为只有 1 然后你可以将它标记为单例但你必须让它Thread-安全,因为它将在线程之间共享.

If you have a need to restrict instances of a controller to only 1 then you can mark it a singleton BUT you have to make it Thread-safe since it will then be shared between threads.

我认为 Activator 模板可以用更多的文档来解释为什么它们似乎在似乎不需要时生成 @Singleton 控制器,因为它令人困惑.例如,HomeController(在 Play-Scala 种子中)在没有任何情况下被混淆地声明为 @Singleton.

I think the Activator templates could do with a bit more documentation around them to explain why they seem to generate @Singleton controllers when they do not seem to be needed since it is confusing. HomeController (in the Play-Scala seed) for example is confusingly declared @Singleton when it exhibits no case for it.

一般来说,最好不要使用 @Singleton,除非您对不变性和线程安全有充分的了解.如果您认为您有单例用例,但请确保您正在保护任何共享状态.

In general, it is probably best to not use @Singleton unless you have a fair understanding of immutability and thread-safety. If you think you have a use case for Singleton though just make sure you are protecting any shared state.

简而言之,不要使用@Singleton.

这篇关于为什么在 play 2.5 中使用单例控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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