简体   繁体   中英

How to Handle Singleton Classes in Distributed Environment

When an Application is Distributed across multiple JVMS my single ton class will have multiple instances at each JVM. I have to generate a Unique ID for this purpose i have to use a singleton pattern class. It is Working fine when in a Standalone Environment. How to make a Singleton pattern in distributed environment so that we can use only one instance ?

EDIT: For my application i need to create userid like

if the name is like Pavan Kumar the userid should be pavankumar if in the system already if this userid exists the userid should be like pavankumar1,pavankumar2 etc......

If the multiple requests for users having same name comes across different servers might result in duplicate id. For this purpose i wanted to use a singleton across distributed environemnt.

I have found a solid answer for this question after a long time. It is possible to implement a Singleton in a distributed environment using AKKA toolkit. Details on how to implement can be found from here http://doc.akka.io/docs/akka/2.3.1/contrib/cluster-singleton.html

您可以尝试hazelcast [ doc ]。这个库允许您使用分布式锁和数据结构,您可以使用它来编写单例。

Have you considered using a distributed cache like Java Caching System from Apache Commons or Coherence Cache from Oracle? It may be overkill, but it really depends on what exactly you are wanting to do.

You can use a central place (like database) to generate the ids. Of course you need to do appropriate locking on the resource so that it is modified by only one entity at a time.

If you are going to persist the entity to a db, you can rely on the db sequence to generate you a id; in short invert the solution from having multiple jvm's generate unique id to a single db doing that. Apart from that there are solutions like @nicholas mentioned that can be leveraged depending upon your needs and scale.

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