目录

Java RMI - 快速指南

Java RMI - Introduction

RMI代表Remote Method Invocation 。 它是一种允许驻留在一个系统(JVM)中的对象访问/调用在另一个JVM上运行的对象的机制。

RMI用于构建分布式应用程序; 它提供Java程序之间的远程通信。 它在java.rmi包中提供。

RMI应用程序的体系结构

在RMI应用程序中,我们编写两个程序,一个server program (驻留在服务器上)和一个client program (驻留在客户端上)。

  • 在服务器程序内部,创建一个远程对象,并为该客户端提供该对象的引用(使用注册表)。

  • 客户端程序请求服务器上的远程对象并尝试调用其方法。

下图显示了RMI应用程序的体系结构。

RMI架构

现在让我们讨论一下这种架构的组成部分。

  • Transport Layer - 此层连接客户端和服务器。 它管理现有连接并设置新连接。

  • Stub - 存根是客户端远程对象的表示(代理)。 它驻留在客户端系统中; 它充当客户端程序的网关。

  • Skeleton - 这是驻留在服务器端的对象。 stub与此框架通信以将请求传递给远程对象。

  • RRL(Remote Reference Layer) - 它是管理客户端对远程对象的引用的层。

使用RMI应用程序

以下几点总结了RMI应用程序的工作原理 -

  • 当客户端调用远程对象时,存根会收到最终将该请求传递给RRL的存根。

  • 当客户端RRL收到请求时,它会调用对象remoteRef一个名为invoke()的方法。 它将请求传递给服务器端的RRL。

  • 服务器端的RRL将请求传递给Skeleton(服务器上的代理),最终调用服务器上的所需对象。

  • 结果一直传递回客户端。

编组和解编

每当客户端调用接受远程对象上的参数的方法时,参数都会在通过网络发送之前捆绑到消息中。 这些参数可以是原始类型或对象。 在基本类型的情况下,将参数放在一起并且将标题附加到其上。 如果参数是对象,则将它们序列化。 此过程称为marshalling

在服务器端,打包参数是非捆绑的,然后调用所需的方法。 这个过程称为unmarshalling

RMI注册表

RMI注册表是放置所有服务器对象的命名空间。 每次服务器创建一个对象时,它都会使用RMIregistry(使用bind()reBind()方法)注册该对象。 这些是使用称为bind name的唯一名称注册的。

要调用远程对象,客户端需要该对象的引用。 那时,客户端使用其绑定名称从注册表中获取对象(使用lookup()方法)。

下图说明了整个过程 -

注册处

RMI的目标

以下是RMI的目标 -

  • 最小化应用程序的复杂性。
  • 保护类型安全。
  • 分布式垃圾收集。
  • 最大限度地减少使用本地和远程对象之间的差异。

Java RMI Application

要编写RMI Java应用程序,您必须按照以下步骤操作 -

  • 定义远程接口
  • 开发实现类(远程对象)
  • 开发服务器程序
  • 开发客户端程序
  • 编译应用程序
  • 执行应用程序

定义远程接口

远程接口提供特定远程对象的所有方法的描述。 客户端与此远程接口通信。

要创建远程接口 -

  • 创建一个扩展属于该包的预定义接口Remote的接口。

  • 声明此接口中客户端可以调用的所有业务方法。

  • 由于远程调用期间可能存在网络问题,因此可能会发生名为RemoteException的异常; 丢它。

以下是远程接口的示例。 这里我们定义了一个名为Hello的接口,它有一个名为printMsg()的方法。

import java.rmi.Remote; 
import java.rmi.RemoteException;  
// Creating Remote interface for our application 
public interface Hello extends Remote {  
   void printMsg() throws RemoteException;  
} 

开发实现类(远程对象)

我们需要实现前面步骤中创建的远程接口。 (我们可以单独编写一个实现类,或者我们可以直接使服务器程序实现这个接口。)

开发实现类 -

  • 实现上一步中创建的接口。
  • 为远程接口的所有抽象方法提供实现。

以下是实现类。 在这里,我们创建了一个名为ImplExample的类,并实现了在上一步中创建的接口Hello ,并为此方法提供了打印消息的body

// Implementing the remote interface 
public class ImplExample implements Hello {  
   // Implementing the interface method 
   public void printMsg() {  
      System.out.println("This is an example RMI program");  
   }  
} 

开发服务器程序

RMI服务器程序应实现远程接口或扩展实现类。 在这里,我们应该创建一个远程对象并将其绑定到RMIregistry

开发服务器程序 -

  • 从要调用远程对象的位置创建客户端类。

  • 通过实例化实现类来Create a remote object ,如下所示。

  • 使用名为UnicastRemoteObject的类的exportObject()方法导出远程对象,该类属于java.rmi.server包。

  • 使用属于java.rmi.registry包的LocateRegistry类的LocateRegistry getRegistry()方法获取RMI注册表。

  • 使用名为Registry的类的bind()方法bind()创建的远程对象绑定到Registry 。 对于此方法,将表示绑定名称和导出对象的字符串作为参数传递。

以下是RMI服务器程序的示例。

import java.rmi.registry.Registry; 
import java.rmi.registry.LocateRegistry; 
import java.rmi.RemoteException; 
import java.rmi.server.UnicastRemoteObject; 
public class Server extends ImplExample { 
   public Server() {} 
   public static void main(String args[]) { 
      try { 
         // Instantiating the implementation class 
         ImplExample obj = new ImplExample(); 
         // Exporting the object of implementation class  
         // (here we are exporting the remote object to the stub) 
         Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);  
         // Binding the remote object (stub) in the registry 
         Registry registry = LocateRegistry.getRegistry(); 
         registry.bind("Hello", stub);  
         System.err.println("Server ready"); 
      } catch (Exception e) { 
         System.err.println("Server exception: " + e.toString()); 
         e.printStackTrace(); 
      } 
   } 
} 

开发客户端程序

在其中编写客户端程序,获取远程对象并使用此对象调用所需的方法。

制定客户计划 -

  • 从您想要调用远程对象的位置创建一个客户机类。

  • 使用属于java.rmi.registry包的LocateRegistry类的LocateRegistry getRegistry()方法获取RMI注册表。

  • 使用属于java.rmi.registry包的类Registry的方法lookup()从注册表中获取对象。

    对于此方法,您需要将表示绑定名称的字符串值作为参数传递。 这将返回远程对象。

  • lookup()返回一个remote类型的对象,向下转换为Hello类型。

  • 最后使用获取的远程对象调用所需的方法。

以下是RMI客户端程序的示例。

import java.rmi.registry.LocateRegistry; 
import java.rmi.registry.Registry;  
public class Client {  
   private Client() {}  
   public static void main(String[] args) {  
      try {  
         // Getting the registry 
         Registry registry = LocateRegistry.getRegistry(null); 
         // Looking up the registry for the remote object 
         Hello stub = (Hello) registry.lookup("Hello"); 
         // Calling the remote method using the obtained object 
         stub.printMsg(); 
         // System.out.println("Remote method invoked"); 
      } catch (Exception e) {
         System.err.println("Client exception: " + e.toString()); 
         e.printStackTrace(); 
      } 
   } 
}

编译应用程序

编译应用程序 -

  • 编译远程接口。
  • 编译实现类。
  • 编译服务器程序。
  • 编译客户端程序。

要么,

打开存储所有程序的文件夹,然后编译所有Java文件,如下所示。

Javac *.java

存储程序

执行申请

Step 1 - 使用以下命令启动rmi注册表。

start rmiregistry

开始执行

这将在单独的窗口上启动rmi注册表,如下所示。

单独的窗口

Step 2 - 运行服务器类文件,如下所示。

Java Server

运行服务器

Step 3 - 运行客户端类文件,如下所示。

java Client 

运行客户端

Verification - 一旦启动客户端,您将在服务器中看到以下输出。

产量

Java RMI - GUI Application

在上一章中,我们创建了一个示例RMI应用程序。 在本章中,我们将解释如何创建RMI应用程序,其中客户端调用显示GUI窗口(JavaFX)的方法。

定义远程接口

在这里,我们使用名为animation()的方法定义一个名为Hello的远程接口。

import java.rmi.Remote; 
import java.rmi.RemoteException;  
// Creating Remote interface for our application 
public interface Hello extends Remote { 
   void animation() throws RemoteException; 
}

开发实现类

在此应用程序的Implementation类(远程对象)中,我们尝试使用JavaFX创建一个显示GUI内容的窗口。

import javafx.animation.RotateTransition;  
import javafx.application.Application;  
import javafx.event.EventHandler;   
import javafx.scene.Group;  
import javafx.scene.PerspectiveCamera;  
import javafx.scene.Scene;  
import javafx.scene.control.TextField;  
import javafx.scene.input.KeyEvent;  
import javafx.scene.paint.Color;  
import javafx.scene.paint.PhongMaterial; 
import javafx.scene.shape.Box;  
import javafx.scene.text.Font;  
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;   
import javafx.scene.transform.Rotate;  
import javafx.stage.Stage;  
import javafx.util.Duration;  
// Implementing the remote interface 
public class FxSample extends Application implements Hello {  
   @Override  
   public void start(Stage stage) { 
      // Drawing a Box  
      Box box = new Box();  
      // Setting the properties of the Box  
      box.setWidth(150.0);  
      box.setHeight(150.0);    
      box.setDepth(100.0);  
      // Setting the position of the box  
      box.setTranslateX(350);   
      box.setTranslateY(150);  
      box.setTranslateZ(50);  
      // Setting the text  
      Text text = new Text(
         "Type any letter to rotate the box, and click on the box to stop the rotation");
      // Setting the font of the text  
      text.setFont(Font.font(null, FontWeight.BOLD, 15));      
      // Setting the color of the text  
      text.setFill(Color.CRIMSON);  
      // Setting the position of the text  
      text.setX(20);  
      text.setY(50); 
      // Setting the material of the box  
      PhongMaterial material = new PhongMaterial();   
      material.setDiffuseColor(Color.DARKSLATEBLUE);   
      // Setting the diffuse color material to box  
      box.setMaterial(material);        
      // Setting the rotation animation to the box     
      RotateTransition rotateTransition = new RotateTransition();  
      // Setting the duration for the transition  
      rotateTransition.setDuration(Duration.millis(1000));  
      // Setting the node for the transition  
      rotateTransition.setNode(box);        
      // Setting the axis of the rotation  
      rotateTransition.setAxis(Rotate.Y_AXIS);  
      // Setting the angle of the rotation 
      rotateTransition.setByAngle(360);  
      // Setting the cycle count for the transition  
      rotateTransition.setCycleCount(50);  
      // Setting auto reverse value to false  
      rotateTransition.setAutoReverse(false);   
      // Creating a text filed  
      TextField textField = new TextField();    
      // Setting the position of the text field  
      textField.setLayoutX(50);  
      textField.setLayoutY(100);  
      // Handling the key typed event  
      EventHandler<KeyEvent> eventHandlerTextField = new EventHandler<KeyEvent>() {  
         @Override  
         public void handle(KeyEvent event) {  
            // Playing the animation  
            rotateTransition.play();  
         }            
      };               
      // Adding an event handler to the text feld  
      textField.addEventHandler(KeyEvent.KEY_TYPED, eventHandlerTextField);  
      // Handling the mouse clicked event(on box)  
      EventHandler<javafx.scene.input.MouseEvent> eventHandlerBox =  
         new EventHandler<javafx.scene.input.MouseEvent>() {  
         @Override  
         public void handle(javafx.scene.input.MouseEvent e) {  
            rotateTransition.stop();   
         }  
      };  
      // Adding the event handler to the box   
      box.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandlerBox); 
      // Creating a Group object 
      Group root = new Group(box, textField, text);  
      // Creating a scene object  
      Scene scene = new Scene(root, 600, 300);       
      // Setting camera  
      PerspectiveCamera camera = new PerspectiveCamera(false);  
      camera.setTranslateX(0);  
      camera.setTranslateY(0);  
      camera.setTranslateZ(0);  
      scene.setCamera(camera);   
      // Setting title to the Stage
      stage.setTitle("Event Handlers Example");  
      // Adding scene to the stage  
      stage.setScene(scene);  
      // Displaying the contents of the stage  
      stage.show();  
   }  
   // Implementing the interface method 
   public void animation() {  
      launch();  
   }  
}

服务器程序

RMI服务器程序应实现远程接口或扩展实现类。 在这里,我们应该创建一个远程对象并将其绑定到RMIregistry

以下是此应用程序的服务器程序。 在这里,我们将扩展上面创建的类,创建一个远程对象,并使用绑定名称hello将其注册到RMI注册表。

import java.rmi.registry.Registry; 
import java.rmi.registry.LocateRegistry; 
import java.rmi.RemoteException; 
import java.rmi.server.UnicastRemoteObject; 
public class Server extends FxSample { 
   public Server() {} 
   public static void main(String args[]) { 
      try { 
         // Instantiating the implementation class 
         FxSample obj = new FxSample();
         // Exporting the object of implementation class  
         // (here we are exporting the remote object to the stub) 
         Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);  
         // Binding the remote object (stub) in the registry 
         Registry registry = LocateRegistry.getRegistry(); 
         registry.bind("Hello", stub);  
         System.err.println("Server ready"); 
      } catch (Exception e) { 
         System.err.println("Server exception: " + e.toString()); 
         e.printStackTrace(); 
      } 
   } 
}

客户计划

以下是此应用程序的客户端程序。 在这里,我们获取远程对象并调用其名为animation()方法。

import java.rmi.registry.LocateRegistry; 
import java.rmi.registry.Registry;  
public class Client { 
   private Client() {} 
   public static void main(String[] args) {  
      try { 
         // Getting the registry 
         Registry registry = LocateRegistry.getRegistry(null); 
         // Looking up the registry for the remote object 
         Hello stub = (Hello) registry.lookup("Hello"); 
         // Calling the remote method using the obtained object 
         stub.animation(); 
         System.out.println("Remote method invoked"); 
      } catch (Exception e) {
         System.err.println("Client exception: " + e.toString()); 
         e.printStackTrace(); 
      } 
   } 
}

运行示例的步骤

以下是运行RMI示例的步骤。

Step 1 - 打开存储所有程序的文件夹,并编译所有Java文件,如下所示。

Javac *.java

存储程序

Step 2 - 使用以下命令启动rmi注册表。

start rmiregistry

开始执行

这将在单独的窗口上启动rmi注册表,如下所示。

单独的窗口

Step 3 - 运行服务器类文件,如下所示。

Java Server

运行服务器

Step 4 - 运行客户端类文件,如下所示。

java Client

客户类

Verification - 一旦启动客户端,您将在服务器中看到以下输出。

事件处理程序

Java RMI - Database Application

在上一章中,我们创建了一个示例RMI应用程序,其中客户端调用显示GUI窗口(JavaFX)的方法。

在本章中,我们将举例说明客户端程序如何检索驻留在服务器上的MySQL数据库中的表的记录。

假设我们在数据库details有一个名为student_data的表,如下所示。

+----+--------+--------+------------+---------------------+ 
| ID | NAME   | BRANCH | PERCENTAGE | EMAIL               | 
+----+--------+--------+------------+---------------------+ 
|  1 | Ram    | IT     |         85 | ram123@gmail.com    | 
|  2 | Rahim  | EEE    |         95 | rahim123@gmail.com  | 
|  3 | Robert | ECE    |         90 | robert123@gmail.com | 
+----+--------+--------+------------+---------------------+ 

假设用户的名称是myuser ,密码是password

创建学生班

使用settergetter方法创建一个Student类,如下所示。

public class Student implements java.io.Serializable {   
   private int id, percent;   
   private String name, branch, email;    
   public int getId() { 
      return id; 
   } 
   public String getName() { 
      return name; 
   } 
   public String getBranch() { 
      return branch; 
   } 
   public int getPercent() { 
      return percent; 
   } 
   public String getEmail() { 
      return email; 
   } 
   public void setID(int id) { 
      this.id = id; 
   } 
   public void setName(String name) { 
      this.name = name; 
   } 
   public void setBranch(String branch) { 
      this.branch = branch; 
   } 
   public void setPercent(int percent) { 
      this.percent = percent; 
   } 
   public void setEmail(String email) { 
      this.email = email; 
   } 
}

定义远程接口

定义远程接口。 在这里,我们使用名为getStudents ()的方法定义一个名为Hello的远程接口。 此方法返回一个列表,其中包含Student类的对象。

import java.rmi.Remote; 
import java.rmi.RemoteException; 
import java.util.*;
// Creating Remote interface for our application 
public interface Hello extends Remote {  
   public List<Student> getStudents() throws Exception;  
}

开发实现类

创建一个类并实现上面创建的interface.

这里我们实现Remote interfacegetStudents()方法。 当您调用此方法时,它将检索名为student_data的表的记录。 使用setter方法将这些值设置为Student类,将其添加到列表对象并返回该列表。

import java.sql.*; 
import java.util.*;  
// Implementing the remote interface 
public class ImplExample implements Hello {  
   // Implementing the interface method 
   public List<Student> getStudents() throws Exception {  
      List<Student> list = new ArrayList<Student>();   
      // JDBC driver name and database URL 
      String JDBC_DRIVER = "com.mysql.jdbc.Driver";   
      String DB_URL = "jdbc:mysql://localhost:3306/details";  
      // Database credentials 
      String USER = "myuser"; 
      String PASS = "password";  
      Connection conn = null; 
      Statement stmt = null;  
      //Register JDBC driver 
      Class.forName("com.mysql.jdbc.Driver");   
      //Open a connection
      System.out.println("Connecting to a selected database..."); 
      conn = DriverManager.getConnection(DB_URL, USER, PASS); 
      System.out.println("Connected database successfully...");  
      //Execute a query 
      System.out.println("Creating statement..."); 
      stmt = conn.createStatement();  
      String sql = "SELECT * FROM student_data"; 
      ResultSet rs = stmt.executeQuery(sql);  
      //Extract data from result set 
      while(rs.next()) { 
         // Retrieve by column name 
         int id  = rs.getInt("id"); 
         String name = rs.getString("name"); 
         String branch = rs.getString("branch"); 
         int percent = rs.getInt("percentage"); 
         String email = rs.getString("email");  
         // Setting the values 
         Student student = new Student(); 
         student.setID(id); 
         student.setName(name); 
         student.setBranch(branch); 
         student.setPercent(percent); 
         student.setEmail(email); 
         list.add(student); 
      } 
      rs.close(); 
      return list;     
   }  
}

服务器程序

RMI服务器程序应实现远程接口或扩展实现类。 在这里,我们应该创建一个远程对象并将其绑定到RMI registry

以下是此应用程序的服务器程序。 在这里,我们将扩展上面创建的类,创建一个远程对象并使用绑定名称hello将其注册到RMI注册表。

import java.rmi.registry.Registry; 
import java.rmi.registry.LocateRegistry; 
import java.rmi.RemoteException; 
import java.rmi.server.UnicastRemoteObject; 
public class Server extends ImplExample { 
   public Server() {} 
   public static void main(String args[]) { 
      try { 
         // Instantiating the implementation class 
         ImplExample obj = new ImplExample(); 
         // Exporting the object of implementation class (
            here we are exporting the remote object to the stub) 
         Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);  
         // Binding the remote object (stub) in the registry 
         Registry registry = LocateRegistry.getRegistry(); 
         registry.bind("Hello", stub);  
         System.err.println("Server ready"); 
      } catch (Exception e) { 
         System.err.println("Server exception: " + e.toString()); 
         e.printStackTrace(); 
      } 
   } 
}

客户计划

以下是此应用程序的客户端程序。 在这里,我们获取远程对象并调用名为getStudents()的方法。 它从列表对象中检索表的记录并显示它们。

import java.rmi.registry.LocateRegistry; 
import java.rmi.registry.Registry; 
import java.util.*;  
public class Client {  
   private Client() {}  
   public static void main(String[] args)throws Exception {  
      try { 
         // Getting the registry 
         Registry registry = LocateRegistry.getRegistry(null); 
         // Looking up the registry for the remote object 
         Hello stub = (Hello) registry.lookup("Hello"); 
         // Calling the remote method using the obtained object 
         List<Student> list = (List)stub.getStudents(); 
         for (Student s:list)v { 
            // System.out.println("bc "+s.getBranch()); 
            System.out.println("ID: " + s.getId()); 
            System.out.println("name: " + s.getName()); 
            System.out.println("branch: " + s.getBranch()); 
            System.out.println("percent: " + s.getPercent()); 
            System.out.println("email: " + s.getEmail()); 
         }  
      // System.out.println(list); 
      } catch (Exception e) { 
         System.err.println("Client exception: " + e.toString()); 
         e.printStackTrace(); 
      } 
   } 
}

运行示例的步骤

以下是运行RMI示例的步骤。

Step 1 - 打开存储所有程序的文件夹,并编译所有Java文件,如下所示。

Javac *.java   

存储程序

Step 2 - 使用以下命令启动rmi注册表。

start rmiregistry

开始执行

这将在单独的窗口上启动rmi注册表,如下所示。

单独的窗口

Step 3 - 运行服务器类文件,如下所示。

Java Server

运行服务器

Step 4 - 运行客户端类文件,如下所示。

java Client

客户端文件
↑回到顶部↑
WIKI教程 @2018