Java RMI(远程方法调用)

1、Java RMI - 简介

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

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

1.1 RMI应用程序的体系结构

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

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

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

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


现在让我们来讨论这个架构的组件。

  • 传输层 (Transport Layer)- 该层连接客户端和服务器。它管理现有的连接,并建立新的连接。

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

  • 骨架(Skeleton) - 这是驻留在服务器端的对象。存根与该骨架通信以将请求传递给远程对象。

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

1.2 RMI应用程序的工作

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

  • 当客户端调用远程对象时,它被最终传递给RRL的存根接收。

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

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

  • 服务器端的执行结果传回客户端。

1.3 编组和解组

每当客户端调用一个接受远程对象参数的方法时,这些参数就会在通过网络发送之前被绑定到消息中。这些参数可以是原始类型或对象。在原始类型的情况下,这些参数放在一起并附上一个标题。如果参数是对象,那么它们将被序列化。这个过程被称为编组

在服务器端,打包的参数被拆开,然后调用所需的方法。这个过程称为解组

1.4 RMI注册表

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

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

下面的插图解释了整个过程 -

1.5 RMI的目标

以下是RMI的目标 -

  • 尽量减少应用程序的复杂性。
  • 保持类型安全。
  • 分布式垃圾收集。
  • 尽量减少使用本地和远程对象的差异。

2、编写Java RMI应用程序

要编写RMI Java应用程序,您必须遵循以下步骤 -

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

2.1 定义远程接口

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

创建远程接口 -

  • 创建一个扩展属于包的预定义接口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;  
} 

2.2 开发实现类(远程对象)

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

开发一个实现类 -

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

以下是一个实现类。在这里,我们已经创建了一个名为类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");  
   }  
} 

2.3 开发服务器程序

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

开发一个服务器程序 -

  • 从您希望调用远程对象的位置创建一个客户端类。

  • 通过实例化实现类来创建远程对象,如下所示。

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

  • 使用属于包java.rmi.registryLocateRegistrygetRegistry ()方法获取RMI注册表

  • 使用名为Registry的类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(); 
      } 
   } 
} 

2.4 开发客户程序

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

开发客户端程序 -

  • 从您打算调用远程对象的位置创建一个客户端类。

  • 使用属于包java.rmi.registryLocateRegistrygetRegistry ()方法获取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(); 
      } 
   } 
}

2.5 编译应用程序

编译应用程序 -

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

要么,

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

Javac *.java

2.6 执行应用程序

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

start rmiregistry

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

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

Java Server

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

java Client 

验证  - 只要您启动客户端,您就会在服务器中看到以下输出。

3、Java RMI - GUI应用程序

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

3.1 定义远程接口

在这里,我们正在定义一个名为Hello的远程接口,其中包含一个名为animation()的方法

import java.rmi.Remote; 
import java.rmi.RemoteException;  

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

3.2 开发实现类

在此应用程序的实现类(远程对象)中,我们尝试使用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();  
   }  
}

3.3 服务器程序

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

以下是此应用程序的服务器程序。在这里,我们将扩展上面创建的类,创建一个远程对象,并使用绑定名称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(); 
      } 
   } 
}

3.4 客户程序

以下是此应用程序的客户端程序。在这里,我们正在获取远程对象并调用其名为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(); 
      } 
   } 
}

3.5 运行该示例的步骤

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

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

Javac *.java

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

start rmiregistry

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

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

Java Server

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

java Client

验证 - 只要您启动客户端,您就会在服务器中看到以下输出。

4、Java RMI - 数据库应用程序

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

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

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

+----+--------+--------+------------+---------------------+ 
| ID | NAME   | BRANCH | PERCENTAGE | EMAIL               | 
+----+--------+--------+------------+---------------------+ 
|  1 | Ram    | IT     |         85 | [email protected]    | 
|  2 | Rahim  | EEE    |         95 | [email protected]  | 
|  3 | Robert | ECE    |         90 | [email protected] | 
+----+--------+--------+------------+---------------------+ 

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

4.1 创建一个学生班

使用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; 
   } 
}

4.2 定义远程接口

定义远程接口。在这里,我们正在定义一个名为Hello的远程接口,其中包含一个名为getStudents()的方法此方法返回一个包含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;  
}

4.3 开发实现类

创建一个类并实现上面创建的接口。

这里我们实现Remote接口getStudents()方法当您调用此方法时,它将检索名为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;     
   }  
}

4.4 服务器程序

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

以下是此应用程序的服务器程序。在这里,我们将扩展上面创建的类,创建一个远程对象并使用绑定名称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(); 
      } 
   } 
}

4.5 客户程序

以下是此应用程序的客户端程序。在这里,我们正在获取远程对象并调用名为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(); 
      } 
   } 
}

4.6 运行该示例的步骤

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

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

Javac *.java  

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

start rmiregistry

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

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

Java Server

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

java Client








猜你喜欢

转载自blog.csdn.net/ancony_/article/details/80777540
今日推荐