问题
Recently I have needed to use RMI, and I know enough for what I need to do, but one thing is intriguing me as I revisit this topic. Is it possible to make asynchronous RMI calls to the same service on the server?
Let's say I have n threads on the client and a single server-side object--call it S. S has a single method that I want to call from my client-side threads, but I don't want it to block as it has no shared resource to worry about.
Any ideas? Or is this something that is just better left to other methods?
回答1:
There should be no issues with doing this. It is the equivalent of multiple clients calling the same service at the same time from the service's perspective.
Any server side object should be written to be safe for concurrent access.
回答2:
Probably you should work with something like JMS queue for asynchronic calls on an J2EE architecture. It works perfectly in these cases.
回答3:
Using Redisson framework remote service could be registered on same node with client side Redisson instance and even on same JVM shared with client side Redisson instance.
Let's assume YourServiceImpl
contains method you need to invoke remotely and implements YourService
interface.
YourServiceImpl should be registered in Redisson via RemoteService object:
YourService yourService = new YourServiceImpl();
RRemoteService remoteService = redisson.getRemoteService();
remoteService.register(YourService.class, yourService);
Remote invocations could be made in asynchronous manner with separate interface marked
with @RRemoteAsync
annotation. Method signatures should be match with same methods in remote interface.
Each method should return org.redisson.core.RFuture
object. It extends java.util.concurrent.Future
and java.util.concurrent.CompletionStage
interfaces and
has few useful methods.
public interface YourService {
Long someMethod1(Long param1, String param2);
void someMethod2(MyObject param);
MyObject someMethod3();
}
// async interface for YourService
@RRemoteAsync(YourService.class)
public interface YourServiceAsync {
RFuture<Long> someMethod1(Long param1, String param2);
RFuture<Void> someMethod2(MyObject param);
}
To invoke method remotely use YourServiceAsync
interface:
RRemoteService remoteService = redisson.getRemoteService();
YourServiceAsync asyncService = remoteService.get(YourServiceAsync.class);
RFuture<Long> res = asyncService.someMethod1(12L, "param");
res.thenApply(r -> {
...
});
More documentation is here
来源:https://stackoverflow.com/questions/1902393/asynchronous-java-rmi