Remote Method Invocation (RMI) Principles and examples

Source: Internet
Author: User
Tags object serialization

RMI Introduction

  A remote method call (RMI) is the name of a program on a machine that calls a method on another machine. This gives you a general idea of what RMI is used for, but it's not quite clear. RMI is the cornerstone of a Java-supported distributed system, such as well-known EJB components. RMI is an object-oriented implementation of remote procedure call (RPC), which is implemented through socket communication and object serialization techniques. Here is a quote from Wikipedia about RMI:

The Java Remote method invocation (java RMI) is a Java API that performs Remote method invocation, the O  bject-oriented equivalent of remote procedure calls (RPC), with support for direct transfer of serialized Java classes and Distributed garbage collection.

    1. The original implementation depends on Java Vsan (JVM) class representation mechanisms and it thus only supports Making calls from the one JVM to another. The protocol underlying this java-only implementation is known as Java Remote Method Protocol (JRMP).
    2. In order to support code running in a NON-JVM context, a CORBA version is later developed.

Usage of the term RMI could denote solely the programming interface or may signify both the API and JRMP, IIOP, or another I Mplementation, whereas the term RMI-IIOP (Read:rmi-Over-IIOP) specifically denotes the RMI interface delegating most of t He functionality to the supporting CORBA implementation.
The basic idea of Java RMI, the Distributed Garbage-collection (DGC) protocol, and much of the architecture underlying the Original Sun implementation, come from the ' Network Objects ' feature of Modula-3.

RMI Fundamentals

  The purpose of RMI is to make calls between objects running on different computers behave like local calls. RMI applications typically consist of two separate programs: Server programs and client programs. RMI needs to define the definition of the behavior and the implementation of the behavior separately, and allows the behavior definition code and the behavior implementation code to be stored and run on different JVMs. In RMI, the definition of a remote service is stored in an interface that inherits from remote. The implementation code for the remote service resides in the class that implements the definition interface. RMI supports two classes to implement the same remote service interface: One class implements the behavior and runs on the server, while the other class runs on the client as a proxy for a remote service. The client program issues a calling method for the proxy object, and RMI sends the call request to the remote JVM and is further sent to the implemented method. The implementation method sends the result to the delegate and then returns the result to the caller through the proxy.

  RMI constructs three layers of abstraction, covering the lower levels, respectively, responsible for socket communication, parameter and result serialization and deserialization. The stub and skeleton (Skeleton) together form the RMI architecture protocol. The following reference layer is used to find the respective communication partner, and at this level there is a section that provides the name service, called the Registry (registry). The next layer is the transport layer, which relies on the TCP/IP protocol to implement the client-server interconnection.
  

When a client invokes a remote object method, the stub is responsible for packaging the method name and its parameter group of the remote object method to be invoked, and forwards the packet down to the server on which the remote object resides, through the remote reference layer and the transport layer. The simple server name service, which is implemented through the RMI Registry of the RMI system, locates the server on which the remote object resides. After the package arrives at the server, it is received by the remote reference layer, Skeleton by the remote object, this Skeleton resolves the method name and the group parameters in the client package, executes the remote object method that the client is invoking on the server side, and then packages the return value (or the resulting exception) of the method back through the reverse route. Back to the client, the Stub of the client returns the result parsed and passed to the client program. In fact, not only the client program can invoke the server-side remote object method through the stub, but the server-side program may also callback the client's remote object method through the remote interface passed by the client. In a distributed system, all computers can be servers, and they can be clients.

RMI Application Example

  The Remote interface is used to identify the interfaces whose methods can be called from a non-local virtual machine. Any remote object must implement this interface directly or indirectly. Only those methods specified in the remote interface (the interface of the extended Java.rmi.Remote) are available for remote use. This means that the method that needs to be called remotely must have a reputation in the interface of the extension remote interface and throw remoteexception exceptions to be called remotely. the remote object must implement the Java.rmi.server.UniCastRemoteObject class to ensure that the client accesses the remote object when it is obtained. The remote object will serialize a copy of itself to the client in the form of a socket, at which point the client obtains the copy called the "stub", while the remote object that the server side itself already exists is called "skeleton". In fact, the stub at this time is a client agent for communication with the server side, and the skeleton can also be considered a proxy on the server side, to receive the client's request after the call to the remote method to respond to the client's request. The interface and implementation of the remote object must be present and consistent on both the client and server side.

Implementation code:

 PackageCom.wxisme.rmi;ImportJava.rmi.Remote;Importjava.rmi.RemoteException;/*** @Description:<p> remote Interface Definition </p> *@authorWang Xu * @time March 14, 2016 PM 4:53:48*/ Public InterfaceHellodefineextendsRemote { PublicString HelloWorld ()throwsremoteexception;  PublicString SayHello (string name)throwsremoteexception; }
 PackageCom.wxisme.rmi;Importjava.rmi.RemoteException;ImportJava.rmi.server.UnicastRemoteObject;/*** @Description:<p> Remote Interface Implementation </p> *@authorWang Xu * @time March 14, 2016 PM 4:57:50*/ Public classHellodefineimpextendsUnicastRemoteObjectImplementsHellodefine {/**     *      */    Private Static Final LongSerialversionuid = 1L;  PublicHellodefineimp ()throwsRemoteException {Super(); }     PublicString HelloWorld ()throwsRemoteException {return"Hello alphago!"; }     PublicString SayHello (string name)throwsRemoteException {return"Hello" + name + "!"; }}
 PackageCom.wxisme.rmi;Importjava.net.MalformedURLException;Importjava.rmi.AlreadyBoundException;Importjava.rmi.Naming;Importjava.rmi.RemoteException;ImportJava.rmi.registry.LocateRegistry;/*** @Description:<p> Server binding </p> *@authorWang Xu * @time March 14, 2016 PM 4:59:33*/ Public classHelloServer {hellodefine Hello;  Public voidServer ()throwsremoteexception, malformedurlexception, alreadyboundexception {Hello=NewHellodefineimp (); //remote Object Registry instanceLocateregistry.createregistry (8888); //registering a remote object on the RMI registration serverNaming.bind ("Rmi://localhost:8888/hello", hello); System.out.println ("Server: Object binding succeeded!" "); }}
 PackageCom.wxisme.rmi;Importjava.net.MalformedURLException;Importjava.rmi.Naming;Importjava.rmi.NotBoundException;Importjava.rmi.RemoteException;/*** @Description:<p> Client call </p> *@authorWang Xu * @time March 14, 2016 PM 5:08:51*/ Public classhelloclient { PublicHellodefine Hello;  Public voidClient ()throwsmalformedurlexception, RemoteException, notboundexception {//finding the specified object in the RMI registryHello = (hellodefine) naming.lookup ("Rmi://localhost:8888/hello"); //invoking a remote object methodSYSTEM.OUT.PRINTLN ("Client:");        System.out.println (Hello.helloworld ()); System.out.println (Hello.sayhello ("The Hand of God")); }}
 PackageCom.wxisme.rmi;Importjava.net.MalformedURLException;Importjava.rmi.AlreadyBoundException;Importjava.rmi.NotBoundException;Importjava.rmi.RemoteException;Importorg.junit.Test;/*** @Description:<p> Test </p> *@authorWang Xu * @time March 14, 2016 PM 5:14:36*/ Public classrmitest {@Test Public voidTestServer ()throwsremoteexception, Malformedurlexception, alreadyboundexception {helloserver server=NewHelloServer ();        Server.server ();  while(true); } @Test Public voidTestClient ()throwsmalformedurlexception, RemoteException, notboundexception {helloclient client=Newhelloclient ();    Client.client (); }}

Operation Result:

Resources:

Wikipedia rmi:https://en.wikipedia.org/wiki/java_remote_method_invocation

Java RMI framework: http://haolloyin.blog.51cto.com/1177454/332426/

"RMI-based file upload and download implementation" Cheng, Xu Xiuhua

Remote Method Invocation (RMI) Principles and examples

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.