The understanding of Java RMI

Source: Internet
Author: User
Tags soap stub

Definition of RMI

RPC (remote Procedure Call): A remoting method invocation that provides the ability to distribute a process by invoking a process in another process.

RMI (invocation): Remote method Invocation, which is a step forward on the basis of RPC, provides communication between distributed objects. Allows an object running on one Java virtual machine to invoke a method that runs on another Java Virtual machine object. The two virtual machines can be in different processes running on the same computer or on different computers on the network.

The full purpose of RMI is to simplify the invocation of remote interface objects as much as possible.

RMI greatly enhances the ability of Java to develop distributed applications, such as the use of complex computational methods on other servers, the primary server only need to call, and the real operation is on the other server, and finally return the results of the operation to the primary server, which reduces the burden on the primary server, Increased efficiency (but there are other costs).

RMI Network Model

in the initial phase of design, what we really want is a mechanism where the client programmer makes method calls in the usual way without worrying about sending data to the network or parsing the response. So there is the following network model: Install a proxy on the client for the remote object. An agent is an object that resides in a client virtual machine, as it is to a client program, as if it were a remote object to be accessed . When the client calls this proxy, only the regular method calls are made. The Client Agent is responsible for contacting the server using the network protocol.

The question now is how does the agent communicate? There are usually three ways to do this:

1, CORBA: Through the object request proxy schema, support the method call between objects written in any programming language.

2. SOAP

3, Rmi:java remote method call technology, supports the method call between Java distributed objects.

where CORBA and soap are completely language-independent, they can be written in C, C + +, Java, and RMI is only available in Java.

How RMI works first, terminology introduction

1. Stub: When a client wants to invoke a method of a remote object, it actually calls a generic method on the proxy object, which we call the stub. the stub is on the client machine, not on the server.

2. Parameter group: The stub will package the parameters required by the remote method into a set of bytes , and the process of encoding the parameters is called a parameter group. The purpose of the parameter grouping is to convert the parameters into a format suitable for passing between virtual machines, in which the object is encoded using the serialization mechanism.

second, the programming model

To introduce the RMI programming model, I'll write a demo below. A remote object represents a warehouse, and the client program asks the warehouse for the price of a product.

1. Interface Definition

The ability of a remote object is represented by an interface that is shared between the client and the server:

 Package RMI; Import Java.rmi.Remote; Import java.rmi.RemoteException;  Public Interface extends remote{    doublethrows  remoteexception;}

The interface of the remote object must extend the remote interface, which is located in the Java.rmi package. All methods in the interface must declare a RemoteException exception to be thrown. This is because the remote method always has the potential to fail, so the Java programming language requires that every call to a remote method must capture RemoteException and indicate the appropriate processing action to take when the call is unsuccessful.

2, the implementation of the interface
 PackageRMI;Importjava.rmi.RemoteException;ImportJava.rmi.server.UnicastRemoteObject;ImportJava.util.HashMap;ImportJava.util.Map; Public classWarehouseimplextendsUnicastRemoteObjectImplementswarehouse{Private Static Final LongSerialversionuid = 1L; PrivateMap<string,double>prices; protectedWarehouseimpl ()throwsRemoteException {Prices=NewHashmap<string,double>(); Prices.put ("Mate7", 3700.00); }     Public DoubleGetPrice (String description)throwsremoteexception {Double price=prices.get (description); returnPrice = =NULL? 0: Price; }}

You can see that this class is the target of a remote method invocation because it extends from UnicastRemoteObject, a constructor of this class that makes its objects available for remote access.

3. RMI registry: Publish RMI Services via Jndi

1. To access a remote object on the server, the client must first obtain a local stub object, which is the proxy object on the client machine. So the question is, how do you get the stub?

2. To this end, the JDK provides a bootstrap registration service (bootstrap-Registry service), and the server program should use the bootstrap registration service to register at least one remote object.

3. To register a remote object, you need an RMI URL and a reference to the implementation object.

4, RMI URL with rmi: Start, followed by the domain name or IP address (host), followed by the port number (port), and finally the service name.

such as: Rmi://regserver.mycompany.cmo:99/central_warehouse

If we are in this              to publish RMI service, then host is "localhost", in addition RMI default port number is "1099", of course, we can also set itself, as long as not with the other ports to repeat. The service is actually based on the same host and Port under the only name.

To publish the RMI service:

1  PackageRMI;2 3 Importjava.net.MalformedURLException;4 Importjava.rmi.AlreadyBoundException;5 Importjava.rmi.Naming;6 Importjava.rmi.RemoteException;7 ImportJava.rmi.registry.LocateRegistry;8 9 Importjavax.naming.NamingException;Ten  One  A  Public classWarehouseserver - { -      Public Static voidMain (string[] args)throwsremoteexception, Namingexception, malformedurlexception, Alreadyboundexception the     { -SYSTEM.OUT.PRINTLN ("Constructing Server Implementation"); -Warehouseimpl Centralwarehouse =NewWarehouseimpl (); -          +SYSTEM.OUT.PRINTLN ("Binding Server implementation to registry"); -Locateregistry.createregistry (1099); +Naming.bind ("Rmi://localhost:1099/central_warehoues", centralwarehouse); A          atSystem.out.println ("Waiting for invocations from clients ..."); -     } -}

Operation Result:

 for invocations from clients ...

1. Line 20th simply provides a port, and a registry is created in Jndi.

2. The 21st line binds the RMI address and the RMI service implementation class through the Bind method.

3, after the implementation of this method, equivalent to automatically released the RMI service. The next thing to do is write an RM client to invoke the published RMI service.

4. Call RMI Service
1  PackageRMI;2 3 Importjava.net.MalformedURLException;4 Importjava.rmi.Naming;5 Importjava.rmi.NotBoundException;6 Importjava.rmi.RemoteException;7 Importjavax.naming.NamingException;8 9  Public classwarehouseclientTen { One      Public Static voidMain (string[] args)throwsnamingexception, RemoteException, malformedurlexception, Notboundexception A     { -System.out.println ("RMI Registry binding:"); -String url = "Rmi://localhost:1099/central_warehoues"; theWarehouse Centralwarehouse =(Warehouse) naming.lookup (URL); -String descr = "Mate7"; -         DoublePrice =Centralwarehouse.getprice (DESCR); -System.out.println (Descr + ":" +Price ); +     } -}

Operation Result:

RMI Registry binding:mate7:3700.0

1, service calls only need to know two things: 1, RMI request path; 2, RMI Interface name

2, line 15th, here is the interface name warehouse, not the implementation class. Must not be the implementation class of the RMI interface, otherwise it is called locally.

3. To view the results of the operation, we know that the remote call of the demo demonstration was successful.

5. Let's look at the RMI network below:

1. With Jndi, the so-called Naming and directory service, we successfully published and invoked the RMI service. In fact, Jndi is a registry where the server puts the service object into the registry and the client obtains the service object from the registry.

2, on the server side we released the RMI service, and registered in Jndi, at this time created a skeleton (skeleton) on the server, when the client successfully connected to Jndi and the remote service object, immediately after the local create a stub (stub).

3, the remote communication is actually through the skeleton and stub to complete, the data is based on the TCP/IP protocol, on the "Transport layer" sent.

4, undoubtedly, theoretically RMI must be faster than WebService, after all, WebService is based on the HTTP protocol, and HTTP carries the data through the "Application layer" to transmit. The transport layer is lower than the application layer, the lower the lower the faster.

The limitations of RMI

1, can only implement the call between the Java system, and WebService can implement cross-language implementation of the system between the call.

2. RMI uses a Java default serialization method, and for systems with high performance requirements, other serialization schemes may be required to resolve.

3. The RMI service will inevitably fail at run time, for example, if the RMI service cannot connect, it will cause the client to fail to respond.

The understanding of Java RMI

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.