RMI的定义
RMI远程方法调用(Remote Method Invocation),它支持存储于不同地址空间的程序级对象之间彼此进行通信,实现远程对象之间的无缝远程调用。
RMI实践案例
服务端
package hello;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* 必须继承Remote接口。
* 所有参数和返回类型必须序列化(因为要网络传输)。
* 任意远程对象都必须实现此接口。
* 只有远程接口中指定的方法可以被调用。
*/
public interface IHelloWorld extends Remote {
String sayHelloToSomeBody(String someBodyName) throws RemoteException;
}
package hello;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
/**
* 服务器端实现远程接口。
* 必须继承UnicastRemoteObject,以允许JVM创建远程的存根/代理。
*/
public class HelloWorldImpl extends UnicastRemoteObject implements IHelloWorld {
protected HelloWorldImpl() throws RemoteException {
super();
}
@Override
public String sayHelloToSomeBody(String someBodyName) throws RemoteException {
System.out.println("hello world!");
return "你好," + someBodyName + "!";
}
}
package hello;
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
public class HelloServer {
public static void main(String[] args) throws Exception {
//创建远程对象
IHelloWorld helloWorld = new HelloWorldImpl();
//注册远程对象
LocateRegistry.createRegistry(8888);
//如果配置在远程服务器,把地址换成你的ip
System.setProperty("java.rmi.server.hostname","127.0.0.1");
Naming.bind("rmi://localhost:8888/Hello", helloWorld);
System.out.println("远程IHello对象绑定成功!");
}
}
客户端
package hello;
import java.rmi.Naming;
public class HelloClient {
public static void main(String[] args) throws Exception {
//访问服务器并查找注册的远程的对象
IHelloWorld helloWorld = (IHelloWorld) Naming.lookup("rmi://127.0.0.1:8888/Hello");
///调用远程对象的方法
System.out.println(helloWorld.sayHelloToSomeBody("666"));
}
}