Java RMI (Remote Method Invocation), rmiinvocation

Source: Internet
Author: User

Java RMI (Remote Method Invocation), rmiinvocation

RMI knowledge
RMI is short for Remote Method Invocation-Remote Method call. Java RMI is implemented in JDK. Its power is reflected in its powerful ability to develop distributed network applications, is one of the core solutions for Java-only distributed network application systems. In fact, it can be regarded as the Java version of RPC. However, traditional RPC cannot be well applied to distributed object systems. Java RMI supports communication between Program-level objects stored in different address spaces to achieve seamless remote calls between remote objects.
RMI currently uses Java Remote message exchange Protocol JRMP (Java Remote Messaging Protocol) for communication. JRMP is designed for Java objects. Java RMI has the advantages of "Write Once, Run Anywhere" in Java and is a pure Java solution for distributed application systems. Application systems developed using Java RMI can be deployed on any platform that supports JRE (Java Run Environment Java, runtime Environment. However, because JRMP is designed for Java objects, RMI does not support application systems developed in non-Java languages. It cannot communicate with objects written in non-Java languages.
RMI can use the standard Java local method interface JNI to connect to the existing and original systems. RMI can also use standard JDBC packages to connect to existing relational databases. The combination of RMI/JNI and RMI/JDBC can help you use RMI to communicate with existing servers that currently use non-Java languages, java can be used on these servers as needed. RMI helps you make full use of the powerful functions of Java during extended use.

I. Composition of RMI (remote method call)
A normally working RMI system consists of the following parts:
· Remote service interface definition
· Specific implementation of remote service interfaces
· Pile (Stub) and framework (Skeleton) files
· A server running remote services
· An RMI naming service that allows clients to discover this remote service
· File provider (an HTTP or FTP Server)
· A client program that requires this remote service

Ii. RMI (remote method call) Principle


The method call is passed down to the host from the client object through the placeholder Program (Stub), Remote Reference Layer (Remote Reference Layer), and Transport Layer (Transport Layer), and then to the host again through the transmission Layer, go up through the Remote Call layer and the backbone network (Skeleton) to reach the server object. The placeholder program acts as the proxy of the remote server object so that the object can be activated by the customer. The remote reference layer processes semantics, manages communication between single or multiple objects, and determines whether a call should be sent to one server or multiple objects. The Transport Layer manages the actual connections and traces remote objects that can receive method calls. The server-side Backbone Network calls the actual method of the server object and obtains the return value. The returned values are transmitted back to the client through the remote reference layer and the transmission layer on the server side, and then back to the transmission layer and remote call layer. Finally, the placeholder program obtains the returned value.
To complete the preceding steps, you need to perform the following steps:
1. Generate a remote interface
2. implement remote objects (server programs)
3. Generate placeholder program and backbone network (server program)
4. Write server programs
5. Write customer programs
6. Register a remote object
7. Start a remote object

Iii. Advantages of RMI
From the basic perspective, RMI is a Remote Procedure Call (RPC) mechanism in Java. Compared with traditional RPC systems, RMI has several advantages because it is part of Java object-oriented methods. Traditional RPC systems use neutral languages, so they are the most common systems-they cannot provide all the functions available on the target platform.
RMI uses Java as the core and can be connected to the existing system using the local method. This means that RMI can provide you with distributed computing technology in a natural, direct, and comprehensive way, this technology can help you add Java functions to the entire system in an increasing and seamless manner.
RMI has the following advantages:
Object-oriented: RMI can pass complete objects as parameters and return values, not just predefined data types. That is to say, you can pass complex types like Java hash tables as a parameter. In the current RPC system, you can only rely on the client to break down such objects into basic data types, pass these data types, and then recreate the hash table on the server. RMI does not require additional Client program code (breaking objects into basic data types) and directly transmits objects across the network.
Movable Property: RMI can move the property (class Implementation Program) from the client to the server or from the server to the client. This gives you the maximum flexibility, because you only need to write a new Java class and install it on the server host once when the policy changes.
Design method: the object transfer feature allows you to fully utilize the powerful features of object-oriented technology in distributed computing, such as layer-2 and layer-3 structured systems. If you can pass attributes, you can use the object-oriented design method in your solution. All object-oriented design methods rely on different attributes to implement their functions. If the complete objects, including implementation and type, cannot be passed, the advantages provided by the design method will be lost.
Security: RMI uses Java's built-in security mechanism to ensure the security of the user system when downloading and executing programs. RMI uses security management programs designed to protect your systems from malicious small applications, protecting your systems and networks from the destruction of potentially malicious download programs. In severe cases, the server may refuse to download any execution program.
Easy to write and use: RMI makes it easy and easy to write Java remote service programs and Java client programs that access these service programs. The remote interface is actually a Java interface. The service program uses three-line commands to declare itself as a service program. Other aspects are similar to any other Java object. This simple method allows you to quickly compile a complete Distributed Object System Service Program and quickly create software prototypes and earlier versions for testing and evaluation. RMI programming is simple, so maintenance is also simple.
Can be connected to existing/original systems: RMI can interact with existing systems through Java's local method interface JNI. With RMI and JNI, you can write client programs in Java and use existing server programs. When using RMI/JNI to connect to an existing server, you can selectively rewrite any part of the service program with Java, and make the new program fully utilize the Java function. Similarly, RMI can use JDBC to interact with existing relational databases without modifying the existing non-Java source code of the database.
Write Once and run everywhere: RMI is part of the Java "write once and run everywhere" method. Any RMI-based system can be transplanted 100% to any Java virtual machine, and RMI/JDBC systems are no exception. If you use RMI/JNI to interact with the existing system, the code written in JNI can be compiled and run with any Java virtual machine.
Distributed garbage collection: RMI uses its distributed garbage collection function to collect remote service objects that are no longer referenced by any customer program on the network. Similar to garbage collection in Java virtual machines, the distributed garbage collection function allows users to define server objects based on their own needs, and it is clear that these objects will be deleted when they are no longer referenced by the client.
Parallel Computing: RMI adopts multi-threaded processing methods, so that your server can use these Java threads to better process client requests in parallel. Java distributed computing solution: RMI is the core part of the Java platform since JDK 1.1. Therefore, RMI exists in any 1.1 Java virtual machine. All RMI systems use the same public protocol. Therefore, all Java systems can directly communicate with each other without prior protocol conversion.

Iv. Relationship between RMI and CORBA
RMI and CORBA are often considered competing technologies because both provide transparent access to remote distributed objects. However, these two technologies complement each other, and the strengths of one can make up for the weaknesses of the other. The combination of RMI and CORBA produces RMI-IIOP, and RMI-IIOP is the foundation of Java Development on the Enterprise server side. In 1997, IBM and Sun Microsystems launched a cooperation plan to promote Java as an enterprise's development technology. The two companies are particularly focused on how to use Java as a server-side language to generate enterprise-level code that can be integrated into the existing architecture. What is needed is a Remote transmission technology, which has both Java RMI (Remote Method Invocation, Remote Method call) the robustness of less resource occupation and more mature CORBA (Common Object Request Broker Architecture, public Object Request proxy Architecture) technology. Out of this need, the RMI-IIOP has come out, it helps to bring Java language to the current Server Enterprise development mainstream language leading position.

Java RMI is not a new technology (in the Java1.1 era), but it is a very important underlying technology.
The well-known EJB is built on rmi. There are some open-source Remote Call components, and the underlying technology is rmi.

In the era of Web Service and SOA, should every application use clumsy Web Service components for implementation? After comparison and testing, RMI is the simplest, it is most suitable for some small applications.

The following is a simple example to describe the principles and applications of RMI. The example below is a simple HelloWorld, but covers the core applications and development modes of RMI.

Interface code

1 public interface IHello extends Remote{2     3     public String helloWorld() throws RemoteException;4     5     public void sayHelloToSomebody(String somebody) throws RemoteException;6 }

Implementation class:

 1 public class Hello extends UnicastRemoteObject implements IHello/*,Serializable*/ { 2  3     public Hello() throws RemoteException { 4         super(); 5         // TODO Auto-generated constructor stub 6     } 7  8     @Override 9     public String helloWorld() throws RemoteException {10         return "helloWorld";11     }12 13     @Override14     public void sayHelloToSomebody(String somebody) throws RemoteException {15         System.out.println("hello "+somebody+"!");16     }17 18 }

 

Server:

1 public class HelloServer {2 public static void main (String [] args) {3 4 try {5 // create a remote object 6 IHello hello Hello = new hello (); 7 8 // remote object Registry instance on the local host, and specify the port to 8888, this step is necessary (Java default port is 1099), an indispensable step, if the registry is not created, you cannot bind an object to the remote registry. createRegistry (8888); 10 // register the remote object to the RMI registration server and name it hello 11 Naming. bind ("rmi: // localhost: 8888/hello", hello); 12 13 System. out. println ("server bound successfully"); 14 15} catch (Remote Exception e) {16 System. out. println ("an Exception occurred when creating a remote object! "); 17 // TODO Auto-generated catch block18 e. printStackTrace (); 19} catch (MalformedURLException e) {20 System. out. println (" URL malformed! "); 21 // TODO Auto-generated catch block22 e. printStackTrace (); 23} catch (AlreadyBoundException e) {24 System. out. println (" An error occurred while binding duplicate objects! "); 25 // TODO Auto-generated catch block26 e. printStackTrace (); 27} 28} 29}

Client:

Public class HelloClient {public static void main (String [] args) {try {// search for the object named hello in the RMI service registry, and call the method IHello hello = (IHello) Naming. lookup ("rmi: // localhost: 8888/hello"); System. out. println (hello. helloWorld (); hello. sayHelloToSomebody ("lc");} catch (MalformedURLException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (RemoteException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (NotBoundException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}

From the above process, RMI depends closely on the server IP address and port, but it does not know the future Server IP address and port during development, but the client program depends on this IP address and port.
This is also one of the limitations of RMI. There are two ways to solve this problem: one is to solve the problem through DNS, and the other is to expose the IP address to the program code through encapsulation.
The second limitation of RMI is that RMI is a remote call in Java, and the programming languages at both ends must be implemented in Java, for communication between different languages, you can use Web Service or public Object Request proxy system (CORBA.

Java RMI simple example 2
The following describes the RMI application using a file exchange program. This application allows the client to exchange (or download) All types of files from the server. The first step is to define a remote interface. The signature method specified by this interface will be provided by the server and called by the client.

Interface code:

1 public interface IfileUtil extends Remote{2     public byte[] downloadFile(String filename) throws RemoteException;3 }

Implementation Code:

1 public class FileUtilImpl extends UnicastRemoteObject implements IfileUtil {2 3/** 4*5 */6 private static final long serialVersionUID = 9135714109249225l; 7 8 public FileUtilImpl () throws RemoteException {9 10} 11 12 13 @ Override14 public byte [] downloadFile (String filename) throws RemoteException {15 File file = new File (filename ); 16 17 byte [] buffer = new byte [(int) file. length ()]; 18 19 Int size = buffer. length; 20 21 System. out. println ("download file size =" + size + "B"); 22 23 if (size> 1024*1024*10) {// the file size cannot exceed 10 MB, if the file is too large, the exported memory may overflow! 24 25 throw new RemoteException ("Error: <The File is too big!> "); 26 27} 28 29 try {30 31 BufferedInputStream input = new BufferedInputStream (32 33 new FileInputStream (filename); 34 35 input. read (buffer, 0, buffer. length); 36 37 input. close (); 38 39 System. out. println ("Info: <downloadFile () hed execute successful!> "); 40 41 return buffer; 42 43} catch (Exception e) {44 45 System. out. println ("FileUtilImpl:" + e. getMessage (); 46 47 e. printStackTrace (); 48 49 return null; 50} 51 52} 53 54}

Server code:

1 public class FileutilServer {2 public static void main (String [] args) {3 try {4 5 IfileUtil file = new FileUtilImpl (); 6 7 LocateRegistry. createRegistry (8888); 8 /// with this program added, You can do not enable the RMI registration program on the console, 1099 is the default port of RMI service monitoring 9 10 Naming. rebind ("rmi: // localhost: 8888/FileUtilServer", file); 11 12 System. out. print ("Ready"); 13 14} catch (Exception e) {15 16 System. out. println ("FileUtilServer:" + e. getMessage (); 17 18 e. printStackTrace (); 19 20} 21} 22}

Client code:

 1 public class FileutilClient { 2     public static void main(String[] args) { 3         try { 4           IfileUtil ifileUtil =    (IfileUtil) Naming.lookup("rmi://localhost:8888/FileUtilServer"); 5           byte[] bytes = ifileUtil.downloadFile("D:\\tomcat\\RUNNING.txt"); 6            7           if(bytes == null){ 8               System.out.println("the file is empty"); 9               System.exit(0);10           }11           12          System.out.println(bytes.length);13             14             try {15                 File file = new File("copy.java");16                 System.out.println("file.getAbsolutePath() = "17                         + file.getAbsolutePath());18 19                 BufferedOutputStream output = new BufferedOutputStream(20 21                 new FileOutputStream(file.getAbsolutePath()));22 23                 output.write(bytes, 0, bytes.length);24 25                 output.flush();26 27                 output.close();28 29                 System.out.println("~~~~~End~~~~~");30             } catch (FileNotFoundException e) {31                 // TODO Auto-generated catch block32                 e.printStackTrace();33             } catch (IOException e) {34                 // TODO Auto-generated catch block35                 e.printStackTrace();36             }37 38             39         } catch (MalformedURLException e) {40             // TODO Auto-generated catch block41             e.printStackTrace();42         } catch (RemoteException e) {43             // TODO Auto-generated catch block44             e.printStackTrace();45         } catch (NotBoundException e) {46             // TODO Auto-generated catch block47             e.printStackTrace();48         }49     }50 }

 

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.