Java--rmi Remote Procedure call (episode)

Source: Internet
Author: User
Tags object serialization

Reprint Please specify source: http://blog.csdn.net/l1028386804/article/details/45970641
First, the definition

Java RMI: Java remote method Invocation, Java invocation, is an application programming interface for implementing remote procedure calls in the Java programming language. It enables programs that are running on the client computer to invoke objects on the remote server. The Remote method invocation feature enables Java programmers to distribute operations in a network environment. The whole purpose of RMI is to simplify the use of remote interface objects as much as possible.

We know that remote procedure calls (remotely Procedure call, RPC) can be used in a process where one process invokes another process (most likely on another remote host), providing the process's ability to distribute. Java's RMI is a step forward on the basis of RPC, which provides communication between distributed objects.

RMI (remote method invocation) is a method that allows an object running on one Java virtual machine to invoke an object that runs on another Java virtual machine.

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

Second, the principle of work

RMI allows a Java program to invoke the method of a Java object on another computer in the network, so the effect of the call is as if it were called on the local machine. In layman's words: A machine has a class on it, and by remote invocation, the B machine calls the method in this class.

RMI, remote method invocation (invocation) is the backbone of enterprise JavaBeans and is a convenient way to build distributed Java applications. RMI is very easy to use, but it's very powerful.

RMI is based on an interface, and the RMI framework is built on an important principle: defining the interface and defining the specific implementation of the interface is separate. Let's build a simple remote computing service and use its client program through concrete examples.

Third, RMI contains part

The remote service interface defines the specific implementation of the remote Service interface stub and framework (Skeleton) files one RMI naming service for a server running remote services, It allows the client to discover the provider of the remote service class file (an HTTP or FTP server) a client program that requires this remote service

Iv. use

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

Currently the main application is packaged in various Java EE project frameworks, such as SPRING,EJB (both spring and EJB encapsulate RMI technology)

To implement RMI in spring:

① defines the interface of the service on the server side, defines the specific classes to implement these interfaces;

② Use the Org.springframework.remoting.rmi.RmiServiceExporter class to register the service on the server side;

③ uses Org.springframework.remoting.rmi.RmiProxyFactoryBean in the client to realize the proxy function of the remote service;

④ the same class as the server-side service interface in the client-defined access

V. Limitations of RMI

RMI is currently communicating using the Java Remote Message Exchange protocol JRMP (Java remotes Messaging Protocol). JRMP is a protocol developed specifically for Java remote objects, and because JRMP is specifically designed for Java objects, RMI has insufficient support for applications developed in non-Java languages. You cannot communicate with objects written in a non-Java language (meaning that only remote calls to code that are both client and server-side Java programs) are supported.

VI. limitations on the use of RMI

Because both the client and server are written in Java, the requirements for platform compatibility are simply that both sides are running on a version-compatible Java virtual machine.

Vii. calling parameters and return values of remote methods

When invoking a method on a remote object, the client can also pass the object as a parameter, in addition to the data of the original type, which corresponds to the return value, which can return the original type or object, which is implemented through the Java Object Serialization (serialization) technique. (In other words: The parameter or return value must implement the Serializable interface if it is an object)

VIII. basic types of RMI applications

Ix. 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

X. RMI Classes and Interfaces

A Remote interface:

is a markup interface that does not define a method

public Interface remote{}

In RMI, the remote interface declares a set of methods that can be called from a 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 public unless the client is in the same package as the remote interface

2. The method in the remote interface must include RemoteException (or its superclass, ioexcepion, or exception) exception in addition to throwing an application-related one when declaring it

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

Two RemoteObject Abstract class

The remote interface and the serialized serializable interface are implemented, and its subclasses provide RMI server functions.

Three locateregistry final ()

class is used to obtain a reference to a specific host's Bootstrap remote object Registration server program (that is, to create a stub), or to create a remote object registration service program that can receive calls on a specific port.

Server-Side

Providing remote Object Services to other clients

Someservice servcie= ... ;//Remote Object Service

Registry registry=locateregisty.getregistry ();//registry is an interface, he inherits from remote, this method returns the local host on the default registry port 1099 on the remoting object RegistryThe reference. GetRegistry (int port) returns a reference to the remote object REGISTRY by the local host on the specified port; getregistry (String host) returns the specified hostOn the default registry port 1099, the remote object RegistryGetRegistry (String host, int port) returns the specified hostAnd portReference to the remote object Registry registry.bind ("I Serve", service);//bind (String name,remote obj) binds a remote reference to the name specified in this registry. Name: Names associated with this remote reference obj: A reference to a remote object (usually a stub) unbind (String name) removes the binding for name specified in the registry. Rebind (String name,remote obj) rebind If name already exists, but remote does not replace it, and if remote does discard the existing binding lookup (string name) returns the registry bound to the specified name The remote reference, return remotestring[] list () returns an array of the names that are bound in this registry. The array will contain a snapshot of the name of the binding when this method is called in this registry.
Client Side

Provide the appropriate service request to the server.

Registry registry=locateregisty.getregistry (); Someservice servcie= (Someservice) registry.lookup ("I serve"); Servcie.requestservice ();

Four Naming classSimilar to the registry class. Client:

Naming.lookup (String URL)

The URL format is as follows "rmi://localhost/" + remote object reference

server-side:

Registry registry=locateregistry.createregistry (int port);
Naming.rebind ("service", service);

Five Rmisecuritymanager class

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

Before you can download code from a remote host, you must execute the following code to install Rmisecuritymanager:

System.setsecuritymanager (New Rmisecuritymanager ());

Xi. Code Development

In order to write a demo, we are divided into two parts, part of the server-side code, part of the client-side code, the client side of the code is mainly to use the server-side code. Of course this code is very simple, just to illustrate the problem, the use of reality will make more complex.

(a) Our purpose

Build a server-side Java project that contains the remote-side code, defines the interface, defines the interface implementation, and then builds a client-side Java project that uses the methods in the remote service through RMI.

(ii) Our code structure

(iii) remote service Code 1. interface definitions for remote services

The first step is to build and compile the Java code for the Service interface. This interface defines all the functions that provide remote services, the following are the source programs:

Usermanagerinterface.java

  Package cn.com.tt.rmiserver.stub;  Import Java.rmi.Remote;  Import java.rmi.RemoteException;  Import Cn.com.tt.rmiserver.bean.Account;  /**   *  Author Liuyazhuang * * Public  Interface Usermanagerinterface extends remote{public      String GetUserName () throws remoteexception;     Public account Getadminaccount () throws remoteexception; }
Interfaces must inherit from the remote class, and each defined method throws 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;  /**   *  Author Liuyazhuang * * 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.setpass<a href= "http://www.it165.net/edu/ebg/" target= "_blank" class= "Keylink" >word</a> (" 123456 ");         return account;     } }

3. Define a bean

Implements the implements serializable serialization interface. That is, a serializable object that can be transferred on the client and server side.

Account.java

  Package Cn.com.tt.rmiserver.bean;    Import java.io.Serializable;  /**   *  @author Liuyazhuang */Public   class account  implements serializable,cloneable{      private Static final Long serialversionuid = -1858518369668584532l;      Private String username;      Private String pass<a href= "http://www.it165.net/edu/ebg/" target= "_blank" class= "Keylink" >word</a>;           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 server side of the main program portal.

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; /** * @author Liuyazhuang */public class Entry {public static void main (String []args) throws Alreadyboundexcep         tion, 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"); } }

(d) Client-side code exports the server-side account class and interface Usermanagerinterface export to a jar package named: Rmiserverinterface.jar. Import into the client. Project--Right-click--export--java--jar file--next--Select Account class and interface usermanagerinterface--named: Rmiserverinterface.jar such as:

5. Create a new Java Project, import the jar package, and write the client code.

6. Code 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;                  /** * @author Liuyazhuang */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 ("username is" +usermanager.getadminaccount (). GetUserName () + "password" +usermanager.getadminaccoun         T (). GetPassword ());         } catch (RemoteException e) {//TODO auto-generated catch block E.printstacktrace ();         } catch (Notboundexception e) {//TODO auto-generated catch block E.printstacktrace (); }              }  }

7. Run the server-side code first, and then run the client code

Displays the result of the run, the client can run multiple times, each time the server-side object can be obtained. If you need to change the port number if you want to run the client code again, the port number will be displayed if you do not change it.





Java--rmi Remote Procedure call (episode)

Related Article

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.