问题
I need to maintain a simple counter that is unique within the application, for all users and all nodes in a clustered environment. I thought about using the singleton session bean annotation javax.ejb.Singleton like so:
package foo;
import javax.ejb.Singleton;
@Singleton
public class Bean {
private int counter;
[...]
}
This looks simple, but I could not find an answer if this works as desired in a clustered environment. Would every node of the cluster have it's own instance or not?
Of course I could persist the bean in a database, but it's really only a counter and doing so would be overkill. Also, I want the counter to reset on application crash or restart, so persisting it would create more problems than it solves.
回答1:
Would every node of the cluster have it's own instance or not?
Yes, each cluster node will have a different Singleton instance. Therefore, @Singleton annotation is not the solution for your problem.
Take in mind that Java EE specification doesn't define any kind of cluster behavior. You need to search for specific vendor solution to achieve this kind of requirement. Just as an example see this link.
回答2:
You could use hazelcast . It's a distributed in-memory key-value store. Seems like it would be a perfect fit. It also implements JSR-107 which is the JCache spec.
回答3:
Ha singleton is an approach. As an advance, there are some limitations. If you read, you will have a @stateless bean that access to the service through a "getValue()" method. The get value calls a singleton bean's methods and gives to you a value... all right until there.
But if you need to operate with the bean, a strategy should return a SingletonBean instance through get value, but.. you will have more instances of that singleton bean .... and there is the problem.
来源:https://stackoverflow.com/questions/29496451/how-singleton-is-javax-ejb-singleton-in-a-clustered-environment