Lightweight RMI Communication with plain Java SE (Source Sample), without generated stubs or additonal frameworks 📎
It seems like the Plain Old RMI (it is perfect for a new acronym: PORI) is almost forgotten. From time to time I use RMI to establish communication between EJBs and legacy or EJB-container problematic processes like native resources. To establish communication between Java objects in different JVMs you have only to follow the following steps:
1. Definition of the remote (service) interface:
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface HelloWorldService extends Remote{
public String helloFromServer(String greeting) throws RemoteException;
}
2. Implementation of the Interface (the servant). Its implements the business logic. Of course the logic can be also factored out in an independent POJO:
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Date;
public class HelloWorldServant extends UnicastRemoteObject implements HelloWorldService{
protected HelloWorldServant() throws RemoteException {
super();
}
public String helloFromServer(String greeting) {
System.out.println("Request received: " + greeting);
return greeting + " time: " + new Date();
}
}
3. You need also a class with a main method...(the actual server)
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class RemoteServer {
public static void main(String[] args) throws Exception {
Registry registry = LocateRegistry.createRegistry(1200); // this line of code automatic creates a new RMI-Registry. Existing one can be also reused.
System.out.println("Registry created !");
registry.rebind("hugo",new HelloWorldServant());
System.out.println("Server is up and running !");
}
}
4. ...and finally the client:
import java.rmi.Naming;
import com.abien.rmi.server.HelloWorldService;
public class HelloWorldClient {
public static void main(String[] args) throws Exception{
HelloWorldService helloWorldService = (HelloWorldService) Naming.lookup("rmi://localhost:1200/hugo");
System.out.println("Output" + helloWorldService.helloFromServer("hello "));
}
}
And now its time for the homework. Just implement the same stuff with SOAP or other technology, and compare the performance, complexity, amount of classes and additional jars with this solution. So just PORI :-)