首页 > 编程语言 > 详细

Java RMI实践

时间:2019-05-22 11:22:01      阅读:82      评论:0      收藏:0      [点我收藏+]

Java远程方法调用,即Java RMI(Java Remote Method Invocation)。一种用于实现远程过程调用的应用程序编程接口。客户机上运行的程序可以调用服务器上的对象。

一、创建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

  

Java RMI实践

原文:https://www.cnblogs.com/linlf03/p/10904499.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!