Spring Singleton in Clustered Environment

强颜欢笑 提交于 2019-12-04 13:43:32

问题


As discussed in this post, it is not suitable to use singleton in clustered environment (because of multiple singleton objects in different JVMs), this must be true for singletons created by Spring framework.

If that's correct, then we have to be a lot careful using Spring framework to use singleton classes. Can you please tell if this is correct understanding?


回答1:


This is not necessarily the case.

It is a problem to use singletons across separate JVMs if they share meaningful state. For instance, a singleton that stored and issued incrementing IDs would be very dangerous if two separate instances existed on two separate application servers that were both part of the same application.

There is nothing inherent in Spring that makes this more or less tricky to deal with. Your Spring beans (likely services) should aim to maintain as little state as is practical as a matter of good practice. If they need to share state, then you will have to solve this problem just as you would with any other shared state.

A great many people use Spring in clustered environments and do not run into any problems relating to the above. I'm one of them!



来源:https://stackoverflow.com/questions/11300706/spring-singleton-in-clustered-environment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!