java RMI and/or JNDI: binding for objects that are not singletons
OK, I get how to use RMI to bind a singleton server object with a well-known name so that other JVMs can find it.
Let's say I have a number of processes, each running a JVM, and each creating an object supporting the FooRemote
interface, which I wish to expose via RMI. Each process has an unpredictable life cycle that corresponds to something, whether it i开发者_运维百科s from user input, or availability of a resource.
How can I bind these without getting naming collisions? Would using JNDI help?
In effect, what I wish to do is to have a pool of similar objects, each on separate JVMs (reason for doing so is important but beyond the scope of this question). I need a client to be able to enumerate which objects are available, and choose one for further interaction.
(The reason I emphasize the separate JVMs is that if they were all in the same JVM, I could just have a singleton manager that handles the group pool, and make all the group instances accessible through the manager. But I can't do that if the group pool consists of independent instances in separate JVMs. )
It's not very effective, but you can have a singleton manager (factory) in each JVM, which creates and enumerates all the objects in the pool that belong to that JVM.
You obviously have to ask them all to get the full picture. This may or may not be what you want depending on your actual use case. While it's accurate, network traffic and delays affect performance drastically, so don't try this if you're querying the pool a lot more than you update it.
Another solution is to turn your client into a server and allow servers to invoke a callback when the status of the objects in the pool change. This solution is probably more efficient in network traffic but is less up-to-date: if one of the servers terminate abruptly, its objects won't be removed from the pool until you actually try to use them and fail. This behaviour can be improved on by a keepalive call and a timeout to keep track of the availability of servers but obviously at the price of increasing the traffic and the complexity of your solution.
精彩评论