Home >Java >JavaBase >Detailed graphic explanation of Java RMI (with examples)

Detailed graphic explanation of Java RMI (with examples)

尚
forward
2019-12-24 17:33:296030browse

Detailed graphic explanation of Java RMI (with examples)

Java RMI: Java Remote Method Invocation, or Java RMI (Java Remote Method Invocation), is an application programming interface used to implement remote procedure calls in the Java programming language.

It enables programs running on the client to call objects on the remote server. The remote method invocation feature enables Java programmers to distribute operations in a network environment. The entire purpose of RMI is to simplify the use of remote interface objects as much as possible.

We know that Remote Procedure Call (RPC) can be used by one process to call a process in another process (probably on another remote host), thereby providing process distribution capabilities. Java's RMI takes another step forward based on RPC, that is, providing communication between distributed objects.

RMI (Remote Method Invocation) is remote method invocation, which allows an object running on one Java virtual machine to call a method on an object running on another Java virtual machine.

The two virtual machines can be running in different processes on the same computer, or they can be running on different computers on the network.

【JavaRMI】

1. Working principle

RMI allows a Java program to call another computer on the network The method of the Java object of the computer, then the effect of calling it is the same as calling it on the local machine. In layman's terms: There is a class on machine A, and through remote calling, machine B calls the methods in this class.

RMI, Remote Method Invocation (Remote Method Invocation) is the backbone of Enterprise JavaBeans and a convenient way to build distributed Java applications. RMI is very easy to use, but it is very powerful.

The foundation of RMI is the interface. The RMI architecture is based on an important principle: defining the interface and defining the specific implementation of the interface are separate. Below we use specific examples to build a simple remote computing service and a client program that uses it

2. RMI includes:

1. Remote service interface Definition

2. Specific implementation of the remote service interface

3. Stub and Skeleton files

4. A server running the remote service

5. An RMI naming service, which allows the client to discover the remote service.

6. A provider of class files (an HTTP or FTP server)

7. One that requires this Remote service client program

3. What is the purpose of RMI?

The purpose of RMI is to provide services for remote communication between distributed Java applications and provide distribution service.

Currently, the main applications are encapsulated in various J2EE project frameworks, such as Spring, EJB (both Spring and EJB encapsulate RMI technology)

Implement RMI in Spring:

① Define service interfaces on the server side and define specific classes to implement these interfaces;

② Use the org.springframework.remoting.rmi.RmiServiceExporter class on the server side to register services;

③ In The client uses org.springframework.remoting.rmi.RmiProxyFactoryBean to implement the proxy function of the remote service;

④Define a class on the client that accesses the same service interface as the server

four , What are the limitations of RMI?                                                                                      JRMP is a protocol specially developed for Java remote objects. Since JRMP is specially developed for Java objects, RMI has insufficient support for application systems developed in non-Java languages.

Cannot communicate with objects written in non-Java languages ​​(meaning that only remote calls with code in which both the client and server are Java programs are supported).

5. What are the limitations of using RMI?

Since both the client and the server are written in Java, the only requirement for platform compatibility is that both parties run on version compatible Java virtual machine.

6. Parameters and return values ​​of RMI calls to remote methods

When calling methods on remote objects, the client can not only use original type data as parameters In addition, objects can also be passed as parameters, corresponding to the return value, which can return primitive types or objects. These are all implemented through Java's object serialization (serialization) technology. (In other words: if the parameter or return value is an object, it must implement the Serializable interface)

7. Basic model of RMI application

Detailed graphic explanation of Java RMI (with examples)8. RMI architecture

Stub/Framework (Stub/Skeleton) layer: client-side stub and server-side framework;Detailed graphic explanation of Java RMI (with examples)

Remote reference layer: Handling remote reference behavior

Transport layer: Connection establishment and management, and tracking of remote objects

9. RMI Classes and interfaces (classes needed to complete a simple RMI).

Detailed graphic explanation of Java RMI (with examples)

(1) Remote interface: It is a tagged interface that does not define methods

Public interface Remote{}

In In RMI, the remote interface declares the set of methods that can be called from the remote Java virtual machine. The remote interface meets the following requirements:

1. The remote interface must extend the Java.rmi.Remote interface directly or indirectly, and must be declared as public, unless the client and the remote interface are in the same package

2. When declaring a method in a remote interface, in addition to throwing one related to the application, it must also include a RemoteException (or its superclass, IOExcepion or Exception) exception

3. In a remote method declaration, a remote object declared as a parameter or return value must be declared as a remote interface, not as an implementation class of the interface.

(2) The RemoteObject abstract class implements the Remote interface and the Serializable interface. It and its subclasses provide RMI server functions.

(3) The LocateRegistry final() class is used to obtain a reference to the boot remote object registration server program of a specific host (that is, create a stub), or to create a remote object registration service program that can receive calls on a specific port.

Server side: Provide remote object services to other clients

SomeService servcie=……;//远程对象服务

1. Registry registry=LocateRegisty.getRegistry(); //Registry is an interface, it inherits Remote, this method returns local The host's reference to the remote object Registry on the default registry port 1099.

2. getRegistry(int port) returns the reference of the local host to the remote object Registry on the specified port;

3. getRegistry(String host) returns the specified host on the default registry port 1099 Reference to the remote object Registry;

4. getRegistry(String host, int port) returns the reference to the remote object Registry on the specified host and port

5. registry.bind(“I serve",service);//bind(String name,Remote obj) Binds the remote reference to the name specified in this registry. name: the name related to the remote reference obj: a reference to the remote object (usually a stub)

6, unbind (String name) removes the binding of the specified name in the registry.

7. Rebind (String name, Remote obj) rebinds. If the name already exists but the Remote is different, replace it. If the Remote is the same, discard the existing binding.

8. lookup(String name) Returns the remote reference bound to the specified name in the registry, returns Remote

9, String[] list() Returns an array of names bound in this registry. This array will contain a snapshot of the names in this registry that were bound when this method was called.

Client side: Provide corresponding service requests to the server.

Registry registry=LocateRegisty.getRegistry();
SomeService servcie=(SomeService)registry.lookup(“I serve”);
Servcie.requestService();

(4) Naming class is similar to Registry class.

Client:

Naming.lookup(String url)
url 格式如下"rmi://localhost/"+远程对象引用

Server:

Registry registry=LocateRegistry.createRegistry(int port);
Naming.rebind(“service”,service);

(5) RMISecurityManager class

In the RMI reference program, if the security manager is not set, Then stubs and classes can only be loaded from the local classpath, which ensures that the application is not compromised by code downloaded by remote method calls.

The following code must be executed to install RMISecurityManager before downloading code from the remote host:

System.setSecurityManager(new RMISecurityManager());

10. Demo development

In order to write a demo, we are divided into two parts, one part is Part of the server-side code is the client-side code. The client-side code is mainly for using the server-side code. Of course, this code is very simple, just to illustrate the problem. Actual use will be more complicated.

(1) Our purpose

Build a server-side java project, including the remote-side code, define the interface, define the interface implementation, and then create a client-side java project to use the remote side through RMI Methods in end services.

(2) Our code structure

Detailed graphic explanation of Java RMI (with examples)

#(3) Remote service code

1. Remote service interface definition

The first step is to create and compile the Java code of the service interface. This interface defines all the functions of providing remote services. The following is the source program:

UserManagerInterface.java

package cn.com.tt.rmiserver.stub;

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

import cn.com.tt.rmiserver.bean.Account;

public interface UserManagerInterface extends Remote{
    public String getUserName() throws RemoteException;
    public Account getAdminAccount() throws RemoteException;
}

The interface must inherit the Remote class, and each defined method must throw a RemoteException exception. object.

2. Specific implementation of the interface

The second step is to implement the above interface:

UserManagerImp.java

package cn.com.tt.rmiserver;

import java.rmi.RemoteException;

import cn.com.tt.rmiserver.stub.UserManagerInterface;
import cn.com.tt.rmiserver.bean.Account;

public class UserManagerImp implements UserManagerInterface {
    public UserManagerImp() throws RemoteException {

    }
    private static final long serialVersionUID = -3111492742628447261L;

    public String getUserName() throws RemoteException{
        return "TT";
    }
    public Account getAdminAccount() throws RemoteException{
        Account account=new Account();
        account.setUsername("TT");
        account.setPassword("123456");
        return account;
    }
}

3. Define a bean , implements the implements Serializable serialization interface. That is, a serializable object that can be transmitted between the client and server.

Account.java

package cn.com.tt.rmiserver.bean;

import java.io.Serializable;

public class Account implements Serializable,Cloneable{
    private static final long serialVersionUID = -1858518369668584532L;
    private String username;
    private String password;
    
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

4. Define the main program entry on the server side.

Entry.java

package cn.com.tt.rmiserver.entry;

import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import cn.com.tt.rmiserver.UserManagerImp;
import cn.com.tt.rmiserver.stub.UserManagerInterface;

public class Entry {
    public static void main(String []args) throws AlreadyBoundException, RemoteException{
        UserManagerImp userManager=new UserManagerImp();
        UserManagerInterface userManagerI=(UserManagerInterface)UnicastRemoteObject.exportObject(userManager,0);
        // Bind the remote object's stub in the registry
        Registry registry = LocateRegistry.createRegistry(2002);
       
        registry.rebind("userManager", userManagerI);
        System.out.println("server is ready");
        }
}

(4) Client-side code

1、把Server端的Account类和接口UserManagerInterface 导出Export成jar包,命名为:RmiServerInterface.jar。导入到client中。

2、项目——右键——Export——java——jar file——next——选择Account类和接口UserManagerInterface——命名为:RmiServerInterface.jar如下图:

Detailed graphic explanation of Java RMI (with examples)

3. 新建一个java Project,导入jar包,编写客户端代码。

4. 代码

ClientEntry.java

package weiblog.rmi;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import cn.com.tt.rmiserver.stub.UserManagerInterface;

public class ClientEntry {
    
    public static void main(String []args){
        
        try {
            Registry registry = LocateRegistry.getRegistry("localhost",2004);
            UserManagerInterface userManager = (UserManagerInterface)registry.lookup("userManager");
            System.out.println("用户名是"+userManager.getAdminAccount().getUsername()
                    +"密码"+userManager.getAdminAccount().getPassword());
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NotBoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

}

5. 先运行服务器端代码, 然后运行客户端代码,就会显示运行结果,客户端可以运行多次,每次都可以取得服务器端的对象。如果要再次运行客户端代码就需要更改端口号,如果不更改就会显示端口号被占用。

更多java知识请关注java基础教程栏目。

The above is the detailed content of Detailed graphic explanation of Java RMI (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete