RMI remote invocation of JAVA serialization __java

Source: Internet
Author: User
Tags object object serialization

RMI (remote method invocation) is a remote procedure call in Java (Procedure call,rpc) Implementation, is a distributed Java application implementation. Its purpose is to shield developers from the details of different JVMs and network connections, so that objects distributed across different JVMs can be easily communicated with each other as if they exist in a unified JVM. Communication involves the encoding and decoding of data, we do not need to do this for general data types, but it involves more complex data types, such as objects, RMI uses serialization, making the encoding and decoding of data transparent to the developers, we do not need to focus on how the data is transmitted, You can make remote calls only by implementing the relevant methods. First, serialization

The serialization of an object is primarily deserialized using the ObjectOutputStream writeobject (object obj) in Java to serialize and ObjectInputStream ReadObject ().
1, in many applications, some objects need to be serialized, so that they leave the memory space, check the physical hard disk for long-term preservation. For example, the most common is the Web server session object, when there are 100,000 users concurrent access, there may be 100,000 session objects, memory may be too much, so the Web container will be some seesion first serialized to the hard disk, and so on, Then restore the objects saved in the hard disk to memory. Of course, most of the current project storage membership status information will be used memcached.
2. When two processes are communicating remotely, they can send different types of data. Regardless of the type of data, it is transmitted over the network in the form of a binary sequence. The sender needs to convert the Java object into a byte sequence to be routed over the network, and the receiver needs to revert the byte sequence back to the Java object. Here RMI uses this to help us orchestrate the object data information.

The summary has the following advantages: permanently save the object's byte sequence to a hard disk, usually in a file. facilitates the transfer of byte sequences of objects on the network.

package rmitest;

Import java.io.Serializable;

    public class person implements serializable{private static final long serialversionuid = -6379887343250921447l;
    private int id;
    private String name;

    Private String sex;
        Public person () {} public person (int ID, string name, String sex) {super ();
        This.id = ID;
        THIS.name = name;
    This.sex = sex;
    }//getxx ();
Setxx (); }
Package serializetest;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import Java.io.ObjectInputStream;

Import Java.io.ObjectOutputStream;

Import Rmitest.person; public class Testobjserializeanddeserialize {public static void main (string[] args) {Person person = new Pe
        Rson (1, "Ding Shuo", "man");
            try {Serialize (person, "e:/ds.txt");
        Deserialize ("E:/ds.txt");
        catch (Exception e) {e.printstacktrace (); Serialize public static void Serialize (Object object, String path) throws exception{Objectoutputstrea
        M outputstream = new ObjectOutputStream (new FileOutputStream (path));
        Outputstream.writeobject (object);
        Outputstream.flush ();
        Outputstream.close ();
    System.out.println ("Serialization successful!");  ///deserialization public static void deserialize (String path) throws exception{ObjectInputStream InputStream = new
ObjectInputStream (new FileInputStream (path));        person who = (person) inputstream.readobject ();
        Inputstream.close ();
        System.out.println ("Deserialization succeeded!");
        SYSTEM.OUT.PRINTLN ("ID:" +person.getid ());
        System.out.println ("Name:" +person.getname ());
    System.out.println ("Sex:" +person.getsex ());
 }

}

Output results:

File generation:

Note: The entity class must implement a serialization interface and set a serialversionuid. If you do not add the field, after serializing the object, modifying the entity class and deserializing it will cause an error. The Java compiler will automatically give this Class A digest algorithm to generate SERIALVERSIONUID, as long as the file more than one space, the resulting serialversionuid will be very different. So after the modification, the Java compiler generates a serialversionuid for us, and the two version numbers when deserialized are inconsistent. Second, jar command

Jar (Java archive file), where we use a simple interface-oriented programming for more realistic simulation of remote interface calls, including a client and a service side. The server side contains interfaces, implementations, and entity classes, the client introduces interfaces and the jar packages of entity classes, which are invoked by remote interfaces to invoke the implementation classes of the interface. So a brief look at how to use the jar command to package related class files. Of course, MAVEN is used to build jar projects in actual projects.

Example:
jar CVF D:\rmitest.jar D:\workspace\tjfae-v2300-20160410\appTest\bin\rmiTest
This command packs all the files under Rmitest into jars and names them as Rmitest.jar storage with D disk. Of course, you can also specify multiple directories, multiple class files. But there is a disadvantage that the jar we are typing is not typed according to the package directory we want. We decompile a jar as shown below:

The path to the class file in the jar is written according to the path we packed, which causes us to report a path error when referencing the jar package. With this in mind, we can adjust the current directory under DOS to the corresponding position with package, and then execute the package command. First adjust the DOS path to D:\workspace\tjfae-v2300-20160410\appTest\bin, and then execute the following command:
jar CVF D:\rmitest.jar rmitest

At this point we have already typed the jar package we want to prepare for the subsequent remote interface calls. three, RMI remote invocation instance

As described earlier on serialization and how to package with JAR commands, the following example is divided into client and server, the server side contains the implementation of interfaces and interfaces, and the implementation is registered to a service address. The server-side interface and entity classes are then packaged with the jar command, referenced at the client, so that the client has only an interface and does not see a concrete implementation. Here for convenience, the interface and implementation are placed in the same project. But a better way is to write the interface in a project A; To make the project a jar bag; in Project B, we introduce the jar package of project A, implement these interfaces and register the service, Project B is the service end, the jar package of project A is introduced in Project C, the service is injected to the corresponding interface, the project C is the client, and the client is called remotely.

The class files involved in this example are as follows:
Service side:
Person: Entity class, implement serializable serialization;
Personservice: Service interface, inherit remote;
PERSONSERVICEIMP: Service realization, Inherit UnicastRemoteObject, and realize personservice;
Servertest: Register Personservice this service;
Client:
Introduce a well prepared jar pack (Person.class, Personservice.class)
Clienttest: Invoke remote service.

The person above has been posted.
Personservice contains an abstract method of Getperson.

Package rmitest;

Import Java.rmi.Remote;
Import java.rmi.RemoteException;

Public interface Personservice extends Remote {public person

    Getperson () throws remoteexception;

}

Personserviceimp must inherit unicastremoteobject, if you do not inherit this class, then the client each lookup out is a different object, You can do this by adding a member variable to the server and testing it every time you call it off.

Package rmitest;

Import java.rmi.RemoteException;
Import Java.rmi.server.UnicastRemoteObject;

public class Personserviceimp extends UnicastRemoteObject implements Personservice {

    private static final long serial Versionuid = 1L;

    Protected Personserviceimp () throws RemoteException {
        super ();
    }

    @Override Public Person
    Getperson () throws remoteexception {person person
        = new person ();
        Person.setid (1);
        Person.setname ("DS");
        Person.setsex ("M");
        return person;
    }


servertest Service-side registration of this service

Package rmitest;

Import java.rmi.Naming;
Import Java.rmi.registry.LocateRegistry;

public class Servertest {public

    static void Main (string[] arg) {
        try {
            Personservice personservice = new Perso Nserviceimp ();
            Locateregistry.createregistry (6600);
            Naming.bind ("Rmi://127.0.0.1:6600/personservice", Personservice);
        } catch (Exception e) {
            e.printstacktrace ();}}}

Clienttest The client to make a remote call, the client must first introduce a well prepared jar package

 import java.rmi.Naming;
Import Rmitest.person;

Import Rmitest.personservice; public class Clienttest {public static void main (string[] args) {try {Personservice Personserv
            Ice = (Personservice) naming.lookup ("Rmi://127.0.0.1:6600/personservice");
            Person person = Personservice.getperson ();
            System.out.println ("ID:" +person.getid ());
            System.out.println ("Name:" +person.getname ());
        System.out.println ("Sex:" +person.getsex ());
        catch (Exception e) {e.printstacktrace (); }
    }

}

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.