简体   繁体   中英

How to make the Spring bean singleton in distributed environment?

I am learning Spring, and I know that bean will be by default singleton in one application context.But what if we deploy the applications in distributed system? What will be the practical way to achieve singleton since every time a request comes in, it may be routed to a different machines with a different application context?

I have read Singleton in Cluster environment but the answer is about cache.

I guess we can do something like putting the singleton into a central place(like memcached) , and every time we need this bean and serialize and deserialize it from IO, Does this work? But, in my opinion, this will be cost a lot since some object is very "expensive" to transfer.

Thank you!

  • Either your singleton is stateless: then you just re-create the same thing in each node, with no communication between nodes needed;

  • or your singleton is stateful: then you need to distribute its state. This is where memcached or any other of a slew of available distributed caches must be applied. You will still be re-creating the singleton itself in each node independently, but you'll make its internal state reside in the distributed cache.

You can set up your web/app server to make sessions "sticky": once a request is routed to a particular server, all requests in that session go to the same server.

The larger question is: why are you designing and implementing a distributed system this way? A singleton for all can't scale. There's no sense in clustering anything if you insist on this path.

A better solution would be stateless, immutable, functional. Create stateless REST services that model your system.

It depends, if you are going to use the Singleton instance just like a service and you won't store any global variable in it, you won't need to make it distributed.

In some cases that you require the distribution and, therefore, use a cache solution; you may try to optimize your implementation to store minimum data to make it distibuted less costly

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM