Remote Method Invocation
- 다른 JVM상의 Java 프로그램 속에 정의된 메서드를 돌릴 수 있는 방법
RMI의 장점
- 남의 컴퓨터의 메서드를 마음대로 돌릴 수 있다
- 복잡하고 무거운 로직은 서버에서 돌리고, 클라이언트에서는 결과만 반환받는다
아키텍처 구조
- 서버-클라이언트 구조
- 서버
- RMI Registy에 Remote Object 의 메모리 레퍼런스 주소 등록
- 클라이언트
- RMI Registry에 Remote Object의 메모리 레퍼런스 주소 획득
- 해당 주소를 RMI통신에 넣어 메서드를 호출
코드예제
서버
// 1. java.rmi.Remote를 상속받는 User Interface 선언
// 2. 해당 User Interface 내에 메서드 정의. throws RemoteException 필수
interface HelloInterface extends Remote {
public String sayHello(String name) throws RemoteExcpetion
}
// 3. 해당 User Interface를 구현하는 Remote Object를 정의
public class HelloImpl extends UnicastRemoteObject implements ?HelloInterface {
public HelloImpl() throws RemoteException {
super();
}
@Override
public String sayHello(String name) throws RemoteException {
return "Hello,"+name;
}
}
// 4. Remote Object를 RMI Registry에 Binding
public App {
public static void main(String[] args) {
try {
Naming.bind("rmi://localhost/MyRemote", new HelloImpl());
System.out.println("Server is registerd");
} catch (Exception e) {
e.printStackTrace();
}
}
}
클라이언트
// 1. RMI Registry LookUp 및 Remote Object의 레퍼런스 획득
HelloInterface hello = (HelloInterface) Naming.lookup("rmi://주소");
// 2. Remote Object의 메서드 수행
String response = hello.sayHello("Jin");
System.out.println(response);
https://jisblee.me/board/view/0/2/164