Java 使用RMI
Java 使用RMI
Java使用序列化的方式,可以实现远端的方法调用,在分工合作时非常方便。本文记录使用java标准库实现rmi
一、服务端
结构
.
├── pom.xml
├── src
│ ├── main
│ │ └── java
│ │ └── hello
│ │ ├── HelloImpl.java
│ │ ├── HelloServer.java
│ │ └── IHello.java
│ └── test
│ └── java
│ └── mycom
│ └── AppTest.java
└── target
IHello.java
package hello;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface IHello extends Remote {
public String sayHelloToSomeBody(String someBodyName) throws RemoteException;
HelloImpl.java
package hello;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class HelloImpl extends UnicastRemoteObject implements IHello {
public HelloImpl() throws RemoteException {
super();
}
public String sayHelloToSomeBody(String someBodyName) throws RemoteException {
System.out.println("Connected sucessfully!");
return "你好," + someBodyName + "!";
}
}
HelloServer.java
package hello;
import java.net.MalformedURLException;
import java.rmi.AlreadyBoundException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
public class HelloServer {
public static void main(String args[]) {
try {
IHello rhello = new HelloImpl();
LocateRegistry.createRegistry(8888);
// 如果配置在远程服务器,把地址换成你的ip
System.setProperty("java.rmi.server.hostname","127.0.0.1");
Naming.bind("rmi://localhost:8888/RHello", rhello);
System.out.println(">>>>>INFO:远程IHello对象绑定成功!");
} catch (RemoteException e) {
System.out.println("创建远程对象发生异常!");
e.printStackTrace();
} catch (AlreadyBoundException e) {
System.out.println("发生重复绑定对象异常!");
e.printStackTrace();
} catch (MalformedURLException e) {
System.out.println("发生URL畸形异常!");
e.printStackTrace();
}
}
}
在服务端启动HelloServer.java就会在8888端口监听请求了
二、客户端
客户端只要分享接口文件就好了
启动代码
package hello;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
public class Client {
public static void main(String args[]) {
try {
// 填写服务器ip
IHello rhello = (IHello) Naming.lookup("rmi://127.0.0.1:8888/RHello");
System.out.println(rhello.sayHelloToSomeBody("Erich"));
} catch (NotBoundException e) {
} catch (MalformedURLException e) {
e.printStackTrace();
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
三、小结
可以看到,客户端只要得到接口文件就能执行操作,而具体的实现交给服务端完成,这种架构可以解耦调用和实现