Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách gửi dữ liệu qua Remote Method (RMI) trong Java

RMI (Remote Method Invocation) cho phép object trong JVM này gọi method của object trong JVM khác. Dùng package java.rmi.

5 Bước xây dựng ứng dụng RMI

Bước 1: Định nghĩa Remote Interface

Kế thừa java.rmi.Remote, các method ném RemoteException.

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Hello extends Remote {
    void printMsg() throws RemoteException;
}

Bước 2: Triển khai Implementation Class (Remote Object)

public class ImplExample implements Hello {
    public void printMsg() {
        System.out.println("This is an example RMI program");
    }
}

Bước 3: Viết Server Program

Tạo remote object, export, bind vào RMI Registry.

import java.rmi.registry.*;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;

public class Server {
    public static void main(String args[]) {
        try {
            ImplExample obj = new ImplExample();
            Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0); // port 0 = random
            Registry registry = LocateRegistry.createRegistry(1099); // Tạo registry port 1099
            registry.bind("Hello", stub);
            System.out.println("Server ready");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Bước 4: Viết Client Program

Lookup stub từ registry, gọi method.

import java.rmi.registry.*;

public class Client {
    public static void main(String[] args) {
        try {
            Registry registry = LocateRegistry.getRegistry("localhost", 1099);
            Hello stub = (Hello) registry.lookup("Hello");
            stub.printMsg();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Bước 5-6: Compile & Run

# Compile all
javac *.java

# Terminal 1: Start RMI Registry (hoặc dùng LocateRegistry.createRegistry trong code Server)
rmiregistry 1099

# Terminal 2: Run Server
java Server

# Terminal 3: Run Client
java Client

Lưu ý hiện đại: RMI là công nghệ cũ (Java 1.1). Thay thế phổ biến: REST API (Spring Boot), gRPC, WebSocket, Message Queue (Kafka, RabbitMQ).