Java远程方法调用,即Java RMI(Java Remote Method Invocation)。一种用于实现远程过程调用的应用程序编程接口。客户机上运行的程序可以调用服务器上的对象。
缺点:只针对Java语言
client: stub
server: skeleton
client与server通过Socket进行双向数据传递。
序列化与反序列化,也叫做: 编码与解密
序列化:将对象转换成字节
反序列化:将字节转换成对象
一、创建RMI程序有4个步骤
1、定义一个远程接口的接口,该接口中的每一个方法必须声明它将产生一个RemoteException异常。
2、定义一个实现该接口的类
3、创建一个服务,用于发布2中定义的类。
4、创建一个客户端,进行RMI调用。
二、程序的实现
1、创建一个Student类。实现Serializable接口,用于信息的传输
public class Student implements Serializable {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2、定义一个接口
public interface IStudentService extends Remote {
List<Student> getStudents() throws RemoteException;
}
3、创建一个实现类
public class StudentServiceImpl extends UnicastRemoteObject implements IStudentService {
protected StudentServiceImpl() throws RemoteException {
}
public List<Student> getStudents() throws RemoteException {
List<Student> students = new ArrayList<>();
for(int i = 1; i < 5; i++){
Student s = new Student();
s.setName("Nick" + i);
s.setAge(i + 20);
students.add(s);
}
return students;
}
}
4、启动服务
public class Start {
public static void main(String[] args) {
try {
IStudentService studentService = new StudentServiceImpl();
LocateRegistry.createRegistry(5000);
Naming.rebind("rmi://127.0.0.1:5000/IStudentService",studentService);
System.out.println("服务已经启动");
}catch (Exception e){
e.printStackTrace();
}
}
}
5、客户端程序调用RMI方法
public class RmiClient {
public static void main(String[] args) {
try{
IStudentService studentService = (IStudentService) Naming.lookup("rmi://127.0.0.1:5000/IStudentService");
List<Student> students = studentService.getStudents();
for (Student s: students){
System.out.println("姓名:" + s.getName() + ",年龄:" + s.getAge());
}
}catch (Exception e){
e.printStackTrace();
}
}
}
显示结果
姓名:Nick1,年龄:21 姓名:Nick2,年龄:22 姓名:Nick3,年龄:23 姓名:Nick4,年龄:24