RMI (Remote Method Invocation)

Concept

RMI helps you to remotely invoke a method from another machine

Pasted image 20221115112940.png

Provides 2 protocols

  • JRMP (native)
    • For Java-to-java
  • CORBA (Common Object Request Broker Architecture)
    • For Java to something else (more painful because you have to convert)

Pasted image 20221115113742.png

Example

Serverside

 public static void main(String[] args) throws RemoteException {
    System.setProperty("java.security.policy", "file:./.java.policy");
    System.setSecurityManager(new SecurityManager());
    try {
      Registry registry = LocateRegistry.createRegistry(8080);
      registry.bind("myFunction", new RemoteFunction());
    } catch (RemoteException | AlreadyBoundException e) {
      throw new RuntimeException(e);
    }

    System.out.println("Hello world");
}

RemoteFunction.java

public class RemoteFunction extends UnicastRemoteObject implements MyRemote {  
  
    public RemoteFunction() throws RemoteException {  
    }  
    @Override  
    public String sayHello() throws RemoteException {  
        System.out.println("Saying hello from remote");  
        return "Saying hello";  
    }  
}

MyRemote.java

public interface MyRemote extends Remote {  
    String sayHello() throws RemoteException;  
}

java.policy

grant codeBase "file:/-" {  
    permission java.security.AllPermission;  
};

ClientSide

public class App {
    @SuppressWarnings("removal")
	public static void main(String[] args) {
    	System.setProperty("java.security.policy", "file:./java.policy");
    	System.setSecurityManager(new SecurityManager());
    	try {
    		Registry registry = LocateRegistry.getRegistry("192.168.1.120", 8080);
			MyRemote myRemote = (MyRemote) registry.lookup("myfunction");
			myRemote.sayHello();
		} catch (RemoteException | NotBoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}

Java policy is the same as the above

Note: Both server and the client needs to have the same folder structure. And sometimes we need to configure a certain properties for it too work. This is too much caveats as modern solution will just use REST and execute over HTTP.