Implementation and application of RMI remote method invocation in Java

Source: Internet
Author: User
Tags stub

Recently, learning Dubbo,rmi is an important underlying mechanism, RMI (remote method invocation) is a kind of communication mechanism between computers that use remote objects to call each other to realize communication between the two parties. With this mechanism, an object on one computer (that is, a JVM virtual machine) can invoke an object on another computer to obtain remote data.

The implementation of RMI is critical to building distributed Java applications and is a very important underlying technology for the Java architecture.

Concept and principle of 1.RMI

The RMI idea is to install a proxy on the client, which is an object in the client virtual machine, and, for client objects, looks like a remote object to be accessed, and the client agent communicates with the server using the network protocol.
The same server will also have a proxy object to communicate with the tedious work.

In RMI, the client's proxy object is called a stub, and the stub is on the client machine, and it knows how to contact the server over the network. The stub packages the parameters required by the remote method into a set of bytes. The process of encoding parameters is called a parameter group (parameter marshalling), and the purpose of the parameter group is to convert the parameters into a form suitable for passing between virtual machines. In the RMI protocol, objects are encoded using the serialization mechanism.

In general, the client stub method constructs a block of information, which consists of the following parts
The identifier of the remote object being used;
Description of the method being called;
The parameters after grouping;

The stub then sends this information to the server. At one end of the server, the sink object performs the following actions:
Locate the remote object to invoke;
Call the required method and pass the parameters provided by the client;
Captures the return value or the exception generated by the call;
Group the return value and package it back to the client stub;
The client stub deserializes the return value or exception from the server side, and the result becomes the call stub return value.

2.RMI Architecture

Pile/FRAME (Stub/skeleton) layer: The client's pile and server-side framework;
Remote reference layer: Handling Remote reference behavior
Transport Layer (transport): Connection creation and management, and tracking of remote objects

3.RMI and proxy mode

The implementation of RMI is a typical proxy mode idea.

(1) UML diagram of proxy mode

The proxy mode provides a proxy for other objects to control access to the object, to split the caller from the callee, and the agent to pass the information to complete the call.
For example, you want to buy the United States version of Iphone6s, friends abroad, to help you bring back the sea, the whole process is the proxy mode, friends as agents, on your behalf to complete the operation you want to do.

The proxy mode can separate the proxy object from the object that is actually called, and reduce the coupling degree of the system to some extent;
acts as a mediator between the client and the target object to protect the target object, and the proxy object can do other things before the target object is called.
Proxy mode adds a proxy object to the client and target object, causing the request to be processed more slowly and increasing the complexity of the system.

(2) Representation of proxy mode in RMI

The internal mechanism of the remote agent is this:

The following RMI instance is actually an application of proxy mode.

A simple example of 4.RMI

The RMI development steps are as follows:
Create the remote interface and declare the remote method, note that this is the interface that implements the communication between the two sides, need to inherit remote
To develop a class to implement remote interfaces and remote methods, it is worth noting that the implementation class needs to inherit UnicastRemoteObject
Compile the file with the Javac command, register the service with the Java-server command, start the remote object
The last client looks for the remote object and calls the remote method

(1) Service-side remote interface
To create a remote interface Searchservice, the interface must inherit the remote class, and each definition method throws a RemoteException exception

Import Java.rmi.Remote; Import  publicinterfaceextends  Remote {    publicthrows  remoteexception;;}

(2) Establish SEARCHSERVICEIMPL to implement remote interface, note that this is a remote object implementation class, need to inherit UnicastRemoteObject

Importjava.rmi.RemoteException; Public classSearchserviceimplImplementssearchservice{/*** Throw RemoteException *@throwsremoteexception*/     PublicSearchserviceimpl ()throwsRemoteException {Super(); } @Override PublicUser Finduser (String ID)throwsRemoteException {/*** Simulation Lookup return Data*/User User=NewUser (ID, "Tom", "18 years old"); returnuser; } }

(3) To establish a model layer for the service, this object needs to be transmitted remotely, so it is necessary to implement the implements serializable serialization interface, which is a serializable object that can be transmitted on the client and server side
Create a new user class for data transfer:

 Public classUserImplementsserializable{Private Static Final LongSerialversionuid = 1L; PrivateString ID; PrivateString name; PrivateString age;  PublicUser (String id,string name,string age) { This. id=ID;  This. name=name;  This. age=Age ; }          PublicString getId () {returnID; }      Public voidsetId (String id) { This. ID =ID; }      PublicString GetName () {returnname; }      Public voidsetName (String name) { This. Name =name; }      PublicString getage () {returnAge ; }      Public voidsetage (String age) { This. Age =Age ; }          PublicString toString () {StringBuffer sb=NewStringBuffer (); Sb.append ("~ User id-" +ID); Sb.append ("~ User name-" +ID); Sb.append ("~ User Age-" +ID); returnsb.tostring (); } }

(4) Set up server side, register RMI communication port and communication path on server side

Importjava.net.MalformedURLException;Importjava.rmi.Naming;Importjava.rmi.RemoteException;ImportJava.rmi.registry.LocateRegistry;ImportJava.rmi.registry.Registry;/** * @authorBingyue*/ Public classProcess { Public Static voidMain (string[] args) {Try{searchservice Searchservice=NewSearchserviceimpl (); //Registering a communication portRegistry Registry=locateregistry.createregistry (5678); //Registering a communication pathNaming.rebind ("Rmi://127.0.0.1:5678/searchservice", Searchservice); System.out.println ("Service start!"); } Catch(RemoteException e) {e.printstacktrace (); } Catch(malformedurlexception e) {e.printstacktrace (); }    } }

(5) Create the client, import the above entity class and interface, call through Naming.lookup ()
If you use the IDE, you can create a new project with the client code as follows:

Importjava.rmi.Naming;/** * @authorBingyue*/ Public classClient { Public Static voidMain (string[] args) {Try {            //call the remote object, note that the RMI path and interface must be consistent with the server configurationSearchservice searchservice= (Searchservice) naming.lookup ("Rmi://127.0.0.1:5678/searchservice"); User User=searchservice.finduser ("100");        System.out.println (User.tostring ()); } Catch(Exception e) {e.printstacktrace (); }    }}

(6) Run the server and client separately to get the result of remote call

(1) Remote interface: is a markup interface that does not define a method

Interface remote{

}

RMI Remote Method invocation implementation and application for Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.