Use RMI to develop Java-based enterprise distributed applications

Source: Internet
Author: User
Tags object serialization
AbstractJava has a wide range of powerful functions such as cross-platform, code portability, security, and efficiency. Therefore, when developing distributed network applications, you can use its own mechanisms to implement distributed computing, a Java-based remote method call (RMI) provides an effective solution for developing enterprise distributed applications.

  KeywordsJava RMI enterprise distributed applications

  Overview

As the informatization construction of power enterprises continues to deepen and develop, the amount of information and data exchange within and between enterprises is greatly increased, the information and data need to be transmitted and exchanged between different computer networks. At the same time, because the existing computer network hardware devices and operating systems vary widely across units and departments, the application level is also uneven, it is particularly important to develop cross-platform, portable, and efficient and secure network-based distributed applications to serve power enterprises.

In today's programming terminology, distributed computing has become a common term that distributes enterprise business data and programs across different physical locations of the network, by mobilizing the processing capabilities of multiple computers on the network, you can call data remotely.

Remote Method Invocation (RMI) allows communication between objects between different Java virtual machines (JVMs. JVM can be located on the same or different computers. in multiple JVMs, one JVM can call methods of objects stored in other JVMs.

This article mainly introduces the features of RMI, analyzes the principles of using RMI for enterprise distributed computing, and the specific steps of using RMI to implement Java-based enterprise distributed applications.

  Features of remote method calling (RMI)

1. disadvantages of TCP Programming

Since the Java programming language was designed to be object-oriented and support the network, the object-based RMI mechanism has been built into the Java platform.

We often use TCP/IP programming in network development, which naturally involves Socket programming. However, using Socket programming requires a lot of repeated encoding, which is very troublesome and error-prone in complicated distributed operations. Therefore, how to perform distributed network computing quickly, efficiently, securely, and elastically is the topic that developers have always pursued and advocated. It was not until RMI emerged that this complicated and inefficient development situation had greatly improved.

2. Features of RMI Programming

When we use Object serialization to allocate objects on the network, RMI provides a unique and powerful distributed computing model that is unmatched by the Java platform. RMI has the following features:

The client can call methods on the remote server like local methods;

You can specify the Client/Server programming contract based on the interface;

The transfer/reverse transfer code can be automatically generated from the default binary file of the server object;

Extends the Java programming model to the machine boundary (beyond the boundary of the Java Virtual Machine (JVM) without any special syntax;

It can also transfer behavior (CODE) together with data in a remote method call ).

Although RMI is not the only enterprise-level Remote Object Access solution, it is the easiest to implement.

3. RMI and CORBA

Cobra, as the specification of the Distributed Application Framework, bears the brunt of being developed by the Object Management Organization (OMG. What is different from CORBA is that it can use different programming languages (such as C/C ++ and basic) to develop distributed applications. RMI is a pure Java solution. In RMI, all parts of the program are written in Java. In this way, the developed program fully complies with Java specifications, facilitating cross-platform access, expansion, and transplantation. According to the situation of the Northwest Electric Power Construction Group Company where the author is located, the server operating systems mainly include Linux and Windows2000 servers, which exist in the company and department respectively. They are different system platforms. At the same time, each project department under the company is far away, nearly dozens of kilometers, and far reaching thousands of kilometers, even outside China, therefore, cross-platform and remote access must be considered when developing enterprise application systems. Rmi can meet programming needs with its own characteristics.

  Introduction to the basic architecture of RMI

RMI uses Socket internally through TCP/IP. as its name implies, RMI can help us find and execute remote object methods. RMI aims to make objects in different JVMs look and act like local objects.

Generally, we call the JVM that calls this remote object as a client, and call the JVM that includes this remote object as a server.

Although the reference to a remote object is different from the reference to obtain the local object, we can use the remote object as a local object. The application does not know whether an object is remote or local. In fact, the method called on the remote object has the same syntax structure as the method called on the local object.

As the underlying layer of RMI (including complex Socket operations), it will automatically intercept method calls, locate remote objects, and then process remote requests. The author believes that the important part of RMI design is that not only the remote access function is designed, but also the transparency of the design.

The basic architecture of RMI consists of three abstraction layers:

1. Stub/framework Layer (Stubs/Skeletons Layer)

RMI introduces two special types of objects, called Stub and Skeleton, which constitute the first layer of RMI.

During remote communication, the TCP/IP protocol should be used for packaging and transmission of many underlying data. Using Java technology, we need to first convert data or objects into byte streams to Facilitate network transmission. This process is called aggregation. When a byte stream is received remotely, we need to convert stream information into objects or data. This process is called unmarshaling, which is just the opposite of aggregation.

The Stub and Skeleton layers are located under the actual application and are built on the Proxy design scheme. Stub is the proxy role implemented by the remote server, Stub is the client object, and Skeleton is used to help objects communicate with Stub through the RMI link, it reads method call parameters from the link, calls the remote service implementation object, accepts the returned value, and then writes the returned value back to Stub.

2. Remote Reference Layer)

The remote reference layer defines the call semantics that supports RMI connections (semantics ).

Jrmp (Java remote method Protocol) is used for remote access to RMI. This layer provides remoteref objects dedicated to jrmp, which are located in Java. RMI. the server package represents a handle of the remote object. Remoteref uses remote reference to call a remote method of a remote object.

3. Transport Layer)

The Transport Layer establishes a stream-based network connection between JVM and is responsible for setting and managing these connections. At this time, RMI uses a wire-level protocol for TCP/IP-based connections. This protocol is the Java remote method protocol (jrmp, namely, Java remote method protocol ).

In JDK 1.2, jrmp no longer requires skeleton, but uses reflection to establish a connection to the remote service. To generate stub, we must use rmic.
In the current RMI implementation, the transport layer is built on TCP/IP and is designed to establish a connection between the customer and the server (even if there is a network obstacle ).

 

Basic Steps for development

We use RMI to write Client/Server mode (Client/Server) applications, including 6 basic steps:

1) define remote interfaces

2) implement remote interfaces

3) Prepare the remote call Server Object

4) generate the residual root stub (customer agent) and framework skeleton (server entity)

5) Use rmiregistry to find remote objects

6) Run and test the RMI Distributed Application

Develop an enterprise information publishing system instance

Before developing RMI for distributed access, you need to modularize various functions, that is, to abstract the actual application into a class and interface model conforming to Java specifications, so that these classes and interfaces can collaborate with each other, independent functions can be implemented. Finally, they can be combined into a unified network distributed system.

Now, we will take the development company's information publishing system as an example. We will tentatively set the name of the main module (main class file) to InfoDistributeService ), to maintain the data consistency and clarity of application development, the names of other modules involved will also be named based on this module.

1. Define remote interfaces

The Java RMI runtime environment requires that any method that can be called remotely be stored in the remote interface.

This remote interface is used to extend java. rmi. remote interface. In Java API, you can find that it does not have any method, but it is a symbolic interface. In this way, you can let the Java Runtime Environment (JRE) understand the special attributes of each interface, this allows remote access.

Therefore, according to the name of the Information Publishing Service (InfoDistributeService), you must first define InfoDistributeRemote as a remote interface, and then put only one method getRemoteInfo () for testing to encode it, add all modules to the newly created enterprise. in the distribute package, the Code is as follows:

// ----------- InfoDistributeRemote. java -------------------
Package enterprise. distribute;
Import java. rmi. Remote;
Import java. rmi. RemoteException;
Public interface InfoDistributeRemote extends Remote {
Public String getRemoteInfo () throws RemoteException;
}

2. implement remote interfaces

This is a class that implements remote objects. If a remote interface is implemented, all methods in the object can be overwritten. Therefore, the remote object implementation class truly contains the code of the method we want to export.

In the remote information publishing system, we implement at least one remote interface object, which is a remote accessible object. Here, the InfoDistributeService class can generate an instance of remote accessible objects for us:

// ----------- InfoDistributeService. java ------------------
Package enterprise. distribute;
Import java. rmi. RemoteException;
Import java. rmi. server. UnicastRemoteObject;
Public class InfoDistributeService
Extends UnicastRemoteObject implements InfoDistributeRemote {
Public InfoDistributeService () throws RemoteException {
Super ();
}
// The return value of the method only for testing...
Public String getRemoteInfo (){
Return "Hello! I am a remote object .";
}
}

The InfoDistributeService class implements the remote interface InfoDistributeRemote and inherits java. rmi. server. UnicastRemoteObject. Because it complies with the InfoDistributeRemote interface, in addition to the constructor method, this class should also have the getRemoteInfo () method, and this method must be implemented.

At the same time, we noticed that the getRemoteInfo () method throws a java. rmi. RemoteException exception. Because many low-level network operations are required during the remote method call process, network errors may occur at any time during the call process, every method in the remote interface (although there is only one getRemoteInfo () method) must throw a RemoteException, And, java. rmi. remoteException must be explicitly handled in the code, that is, all the Code involved in RMI activities should be placed in the try-catch Block.

3. Prepare the server objects for remote calls.

This is a class used as a server. It is relative to the client that wants to access the remote method. It stores the bound strings and objects.

Setting the remote object to accept remote calls is like starting the socket server that listens to the ServerSocket object. In fact, when using RMI, there are many underlying network operations behind the scenes in the TCP/IP protocol transmission mode. But at this moment, users do not need to know these details, but only need to gradually export remote objects:

In a newer version of Java Development Tool JDK 1.4, you can select java. rmi. UnicastRemoteObject or java. rmi. Activation. Activatable. In this example, UnicastRemoteObject is used to establish a one-to-one connection between the client and the server object instance.

4. Generate Stub and Skeleton

The remote transfer code generated by RMI is also included in the file with the extension of. class, just like other Java code.

After RMI is used, the code of the call parameter generated on the client and the reverse call return value is called the residual root (Stub ), the Framework (Skeleton) is the code generated on the server for anti-Transfer Parameters and the transfer return value for actual method calls ).

You can use RMI's built-in command line tool rmic (RMI Compiler) to first scan the remote object's. class file and generate the residual root and framework code. Principle 1 of the rmic tool.

5. remote client: This is a class that helps us access remote methods. It is also an end user. We will call the remote method in this class using the method for searching and calling remote methods.

Typical rmic calls are as follows (in the current directory): with remote interfaces and implementations, you can use rmic to compile classes and generate Stub and Skeleton, use the following code line in the command line window:

// Compile all java source files
Javac enterprise \ distribute \ *. java
// Make stub and skeleton code
Rmic enterprise. distriservice. InfoDistributeService

After running, generate the following files in the current directory (that is, transfer the code ):

InfoDistributeService_Stub.class
InfoDistributeService_Skel.class

5. Use rmiregistry to find remote objects

After exporting the server objects, You can remotely access them, but the client must try to contact these remote objects.

Because distributed applications may involve many different machines, an initial connection must be established between all machine pairs for communication. In other words, an initial remote object must be found, which is executed through the rmiregistry command.

The JDK development tool provides the utility RMI Registry, which is used to maintain mappings between text names and remote objects for remote access.

On the client side, the RMI registry can be accessed through a program using the lookup () Static Method of the same java. rmi. Naming class. For example, if the remote host is iServer, the remote object instance is InfoDistributeService, and the remote port number is 5678, the client searches for the remote InfoDistributeService instance in the remote host iServer, when referencing an instance, you must use the remote interface InfoDistributeRemote. The Code is as follows:

InfoDistributeRemote iServer = (InfoDistributeRemote) Naming. lookup ("rmi: // iServer: 5678/InfoDistributeService ");

On the server side, you can use the java. rmi. Naming class to register the rmiregistry running instance. For example, use the rebind () method to associate the InfoDistributeService instance in iService with the InfoDistributeService name.

InfoDistributeService iService = new InfoDistributeService ();
Naming. rebind ("/InfoDistributeService", iService );

To sum up, InfoDistributeRemote is a Java interface, so iServer is actually a local object instance that implements the InfoDistributeRemote interface. It is not a remote object, but a local representation of the remote InfoDistributeService. That is to say, it is a local instance of the residual root code InfoDistributeService_Stub.class automatically generated by the preceding rmic tool. Figure 3 shows how remote object calls work.


Figure 2 Working Principle of remote object call

As shown in figure 2, the client maintains remote object calls through the iServer variable. In fact, the iServer reference variable is the local reference of the object implementing the InfoDistribute interface. This object is the residual root Implementation of InfoDistributeService. Together with the server framework, this vulnerability is mobilized/reversed through the InfoDistributeRemote interface for all remote calls.

When we regard InfoDistributeService as a local instance implementing the InfoDistributeRemote interface, the residual root code only works behind the scenes, and the implementation becomes very transparent.

Based on the above principles, we can further design and improve the client and server code, and then compile the complete application.

6. Run and test the RMI distributed application.

After confirming that the required modules have been designed, follow these steps to run and test the basic functions of the Information Publishing System (that is, only getRemoteInfo () declared in the remote interface is implemented () method ).

In the aforementioned enterprise. distribute package, run the javac command to compile the source file with the suffix. java.

Javac enterprise/distribute/*. java

Then, use the RMIC tool to generate the residual root and framework.

Rmic enterprise. distriservice. InfoDistributeService

After compilation, you must determine the content of the client and server Release versions. Therefore, you must use the jar command to package the client and server Release versions into. jar files. The command for packaging the Server File is as follows:

Jar cvf InfoDistributeService. jar
Enterprise \ distribute \ InfoDistributeService. class
Enterprise \ distribute \ InfoDistributeRemote. class
Enterprise \ distribute \ InfoDistributeService_Stub.class
Enterprise \ distribute \ InfoDistributeService_Skel.class

Similarly, the client packaging is similar to the above commands.

Run the RMI Application

Complete all the RMI tests in the first phase, and then run the information publishing application. Follow the Java specifications to start the following projects in sequence:

Start RMIRegistry

Run the following command in the Code directory to start the rmiregistry instance on the console.

Start rmiregistry

Start the server

Start the server directly, generate an instance of the InfoDistributeService remote object, and register it with the Registry.

Start java-classpath InfoDistributeService. jar
Enterprise. distribute. InfoDistributeService

Start the client

Finally, run the java-classpath RemoteClient. jar command to start the client, locate the Remote Information Publishing Service through rmiregistry, and obtain the required remote information through remote calls.

  Conclusion

This article briefly describes the features of Java RMI and the main steps for developing enterprise distributed applications using RMI. Taking the remote information publishing system as an example, the principles and implementation processes of Remote Object Access and remote method calling during information publishing are briefly described.

In order to develop more practical enterprise distributed applications, RMI can also implement more powerful functions in combination with Object serialization, providing us with a more flexible and efficient network distributed application system.

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.