http://hedaoyuan.blog.51cto.com/4639772/813702
1.1 RMIThe basic concept of 1.1.1 What is rmirmi (remote method invocation) is a mechanism by which objects between computers invoke each other's functions and initiate the other process, using this mechanism, When an object on one computer calls a method on another computer, the program syntax rules used are the same as the syntax rules for method calls between objects on the local machine. Use of 1.1.2 RMI
1.
Distributed ArchitectureWhy should we use distributed computing? When we want to share a central resource (such as a database) with multiple users or clients, distributed computing is used. Ø distributed computing is used to leverage the combined computing power of multiple systems to solve problems more efficiently or faster than on a single system. Multiple computer systems can be configured in several ways to share processing, including shared memory, shared disks, or simply sharing a common communication channel. The latest technology allows systems that are physically far apart to work together when computing problems are handled. With regard to the use of computational capacity, the advent of the Internet and the accompanying communication protocol, TCP/IP, has made countless computer systems unprecedented in connection. For some applications, the ability to take advantage of so many computational functions to solve problems is satisfying. Even more appealing is that most computer systems have plenty of free time to help solve other problems. In the future, Grid computing will be sold using distributed computing power, which is very similar to selling electricity in the power industry.
2.
Java
distributed Object Programming TechnologyRMI is the backbone of enterprise JavaBeans and a convenient way to build distributed Java applications. As long as the program is designed according to the RMI rules, you can avoid having to ask about the network details under RMI, such as TCP and sockets, and so on. The communication between any two computers is solely the responsibility of RMI. Invoking objects on a remote computer is as convenient as a local object. 1.1.3 RMI Application Classification depending on the responsibilities of the RMI application, the application can be categorized as follows: Ø Server program: The server program creates multiple remote objects and enables each object to be referenced. Waits for a client to invoke a method on a remote object that is created well. Ø client program: Gets a reference to one or more remote objects from the server-side program. The client can invoke the method on the remote object with this reference. Ø equivalent Computing program: The two sides equal status, mutual for each other's servers and clients.1.2To create an RMI application step
1.
defining the Remote interfaceIn Java, a remote object is an instance of a class that implements a remote interface, and the remote interface declares each method to be called remotely. When we need to create a remote object, we pass an interface to hide the implementation details of the base, and the customer sends the message through the interface handle. The remote interface has the following characteristics: Ø The remote interface must be a public property. If this is not the case, unless the client is in the same package as the remote interface, the call will get an incorrect result when attempting to mount a remote object that implements the remote interface. Ø the remote interface must extend the interface java.rmi.Remote. Ø each method in the remote interface must declare java.rmi.RemoteException in its own throws clause, in addition to the exceptions that are specific to the application itself. (or RemoteException's parent class).
code Example 1
Package Com.itjob;import java.rmi.*; Public interface rmisample extends remote{public int sum (int a,int b) throws remoteexception;} |
2.
Implementing a remote interfaceThe remote object implementation class must extend the remote object Java.rmi.UnicastRemoteObject class and implement the defined remote interface. The implementation class for the remote object contains code that implements the remote method specified by each remote interface. This class can also contain additional methods, but the client can only use methods from the remote interface. Because the customer is a handle to the interface, not which class it is. You must define a constructor for a remote object, even if you are only prepared to define a default constructor that calls the underlying class constructor. Because the underlying class constructor may throw Java.rmi.RemoteException, the java.rmi.RemoteException exception must be thrown even if there is nothing to it.
code Example 2
Package Com.itjob.rmi;import java.rmi.*;import java.rmi.server.*;import com.itjob.RmiSample;/** remote interface implementation class, Inherits the UnicastRemoteObject and implements the Rmisample remote interface */public class Rmisampleimpl extends UnicastRemoteObject implements Rmisample {//Overrides the default constructor and throws Remoteexceptionpublic Rmisampleimpl () throws Remoteexception{super ();} All remote implementation methods must throw Remoteexceptionpublic int sum (int a,int b) throws Remoteexception{return a+b;}} |
3.
Writing server ClassesThe class that contains the main method can be either the implementation class itself, or it can be completely another class. The following rmisampleserver is used to create an instance of a remote object and start the registry service from the specified port number through the Createregistry method of the Java.rmi.registry.LocateRegistry class, or by executing The Rmiregistry command starts the registry service, and the default run port for the registry service is 1099.
code Example 3
package Com.itjob.rmi ; import java.rmi.*;import java.rmi.registry.*; public class rmisampleserver{public static void Main (String [] args) {/* Create and install a security manager to support RMI. As part of the Java Development Package * For RMI the only one is Rmisecuritymanager.*if (system.getsecuritymanager () = = NULL) {System.setsecuritymanager (New Rmisecuritymanager ());} */try{locateregistry.createregistry (8808); Rmisampleimpl server=new Rmisampleimpl (); Naming.rebind ("//localhost:8808/sample-server", SERVER); SYSTEM.OUT.PRINTLN ("Remote object registration succeeded, RMI service started, waiting for client to call ....");} catch (java.net.MalformedURLException me) {System.out.println ("Malformed URL:" +me.tostring ());} catch (RemoteException re) {System.out.println ("Remote Exception:" +re.tostring ());} catch (Alreadyboundexception Abe) {System.out.println ("(Alreadybound exception:" + abe.tostring ());}}} |
  |
Ø code example 3 binds the remote object name to a reference to the remote object: Locateregistry.createregistry (8808); Specifies that the RMI service does not use the default port 1099, but instead uses the port 8808 that it specifies. Naming.rebind ("//localhost:8808/sample-server", server), the remote object is registered on the server and the Url,url format that will look for remote object references is specified as//host:port/name. Where host is the hostname (remote or local) where the registry is located, port is the port number that the registry accepts calls, and name is a simple string that is not interpreted by the registry. Both host and port are optional. If host is omitted, the host defaults to localhost. If Port is omitted, the port defaults to 1099 and the port is the "famous" port used by the RMI registry rmiregistry. The results of the code example 3 run:
Figure
14.1
code Example
3
Run Results
4.
writing client classes that use remote servicesThe main functions of the client class are two, one is to construct the registration service program stub program instance through the Naming.lookup method, and the other is to invoke the remote method on the server remote object.
code Example 4
Package Com.itjob.rmi;import Java.rmi.*;import java.rmi.server.*;p ublic class Rmisampleclient {public static void main ( String[] args) {try {String url = "//localhost:8808/sample-server"; Rmisample Rmiobject = (rmisample) naming.lookup (URL); System.out.println ("1 + 2 =" + Rmiobject.sum);} catch (RemoteException exc) {System.out.println ("Error in Lookup:" + exc.tostring ());} catch (Java.net.MalformedURLException exc) {System.out.println ("Malformed URL:" + exc.tostring ());} catch (Java.rmi.NotBoundException exc) {System.out.println ("Notbound:" + exc.tostring ());}}} |
5.
create root and dry for remote object implementationsThe client is using the Naming.lookup method to construct a registry stub program instance that initiates a call to a remote object method through a reference to the instance, so you must create a root (stub) and a dry (Skeleton) for the remote object implementation before running the client app. To create a stub program and skeleton file, run the Rmic compiler with the full name of the compiled class package that contains the remote object implementation. A stub is a proxy for a remote object on the client that passes the RMI call to the server-side skeleton (Skeleton), which is responsible for passing the call to the actual remote method. Run the rmic call under the command-line module:
Figure
.
2
RMIC
CommandCall the Rmic command to run the result:
Figure
14.3 RMIC
Run ResultsØ we can look at the system to help us generate the stub rmisampleimpl_stub.class but the system did not help us build the skeleton (Skeleton) Rmisampleimpl_ Skeleton.class. This is related to the JDK version: Run Rmic Com.itjob.rmi with the JDK1.4 version. Rmisampleimpl command system will generate stub Rmisampleimpl_stub.class and skeleton (Skeleton) Rmisampleimpl_ Skeleton.class two classes of files, run Rmic com.itjob.rmi with JDK1.5 version. Rmisampleimpl command system will only generate stub rmisampleimpl_stub.class, skeleton (Skeleton) Rmisampleimpl_ The function of Skeleton.class will be realized automatically by the system at run time;
8, N
Run the programOnce you have done the above steps in turn, let's run our RMI application now. Run the server-side program first, as shown in result 14.1. Next we run the client program (code example 4) and run the result:
Figure 14.4
client program Run resultsSeeing the results above shows that our client program made the RMI remote call already successful.1.3 RMIIntroduction to interfaces and classes the interfaces and classes that specify the behavior of the RMI system's remote objects are defined in the Java.rmi package, and then we look at several core interfaces and classes:
1.
Java.rmi.Remote
InterfaceIn RMI, the remote interface declares a set of methods that can be called from a remote Java Virtual machine, and the remote interface must meet the following conditions: Ø the remote interface must extend the Java.rmi.Remote interface at least directly or indirectly. Ø the method declaration in the remote interface must be satisfied: The remote method declaration must include the remoteexception exception (or her parent class) in addition to the exception that is associated with the application in its throws clause, in the remote method declaration, A remote object declared as a parameter or a return value must be declared as a remote interface, not an implementation class for that interface.
2.
Java.rmi.RemoteException
classThe RemoteException class is an exception thrown by the RMI runtime during a remote method call, and in an application that uses the RMI system, the remote method declared in the remote interface must specify RemoteException or its superclass in its throws clause. The remoteexception exception is thrown when the remote method call fails for any reason. The Øremoteexception class is a checked exception, not a runtimeexception.
3.
Java.rmi.server.RemoteObject
classØrmi server functions are provided by the RemoteObject class and its subclasses remoteserver,unicastremoteobject and activatabble. Øremoteobject is an object method that is sensitive to remote objects, and the Hashcode,equals and ToString methods provide implementations. Ø create remote objects and export them, the required methods are provided by classes UnicastRemoteObject and activatable, and subclasses can recognize remote methods. Øunicastremoteobject defines a single invocation of a remote object whose reference is valid only when the server process is running. Ø class Activatable is an abstract class that defines a activatable remote object that executes when its remote method is invoked and shuts itself down when necessary.
4.
Java.rmi.registry.LocateRegistry
classThe Locateregistry class is used to obtain a reference to the boot remote object Registration service for a specific host (create stub), or to create a remote object registration service program that can accept calls on a specific port, and the registry service implements the simple naming syntax associated with remote object names Server restarts do not remember the bindings between these names and remote objects. Methods in the Locateregistry class: public static Registry GetRegistry () throws Remoteexceptionpublic static Registry getregistry (int Port) throws Remoteexceptionpublic static Registry GetRegistry (String host) throws Remoteexceptionpublic static Registry GetRegistry (string host, int port) throws remoteexceptionpublic static Registry GetRegistry (string host, int port, RMICL Ientsocketfactory CSF) throws Remoteexceptionpublic static Registry createregistry (int port) throws Remoteexceptionpublic static Registry createregistry (int port, rmiclientsocketfactory CSF, Rmiserversocketfactory SSF) Throws RemoteException
5.
Java.rmi.Naming
classThe naming class provides methods for storing and obtaining references to remote objects in the remote object Registration service program in the Ønaming class as one of the parameters in the form of a URL//host:port/nameø When the remote object is registered with the RMI Registry service on the local host, the calling program on the remote host can query the remote object by name, obtain its reference, and then invoke the remote method on the object. public static Remote lookup (String name) throws Notboundexception, Malformedurexception, Remoteexceptionpublic static void bind (String name, Remote obj) throws Alreadyboundexception, malforedurexception, remoteexceptionpublic static void U Nbind (string name) throws RemoteException, notboundexception,malformedurlexceptionpublic static void Rebind (string Name, Remote obj) throws RemoteException, Malformedurlexception
6.
Java.rmi.server.UnicastRemoteObject
classClass UnicastRemoteObject creates and exports a remote object that implements a remote service that has the following characteristics: Ø The reference to this object is valid only for the lifetime of the process that created the remote object. Ø through TCP Transport and remote object communication calls, parameters and results use the stream protocol to communicate between the client and the server.
7.
Stub
and SkeletonRMI uses standard mechanisms for the communication of remote objects: stubs and skeleton
Figure 14.5 Stub
and SkeletonThe Østub function initializes the connection to the remote machine that contains the remote object. The remote machine parameters are grouped (written and transmitted). Waits for the result of the method call. Reads the return value or returns the exception. Returns the value to the calling program. Øskeleton function in the remote machine, each remote object can have the corresponding Skeleton,skeleton is responsible for assigning the call to the actual implementation of the remote object, his main functions are as follows: Read the parameters of the remote method. Invokes the method on the actual remote object implementation. The result (return value or exception) is grouped (written and transmitted) to the calling program.1.4 JNDIThe rationale for the emergence of the basic concept of jndi seems simple. With the development of distributed application, remote Access object access becomes a common method. Although the remote communication can still be realized through programming means such as socket, it still has its limitations according to the theory of the model. RMI technology, the generation of RMI-IIOP technology, makes the search of remote objects become the focus of technology. Jndi Technology was born. After the Jndi technology is generated, it is easy to find remote or local objects.
1.
JNDI
What is it?JNDI (the Java naming and directory Interface,java naming and directory interface) is a set of APIs that access naming and directory services in Java applications. Provides developers with a common, unified way to find and access various naming and directory services. Through the interface provided by Jndi, the user, machine, network, object service can be located by name. Ø Naming service: Just like DNS, the majority of the Java EE servers have named servers that are serviced by a named server. Ø directory service: A simplified RDBMS system that stores some simple information through the attributes that the directory has. Directory services are implemented through directory servers, such as Microsoft Active Directory.
2.
JNDI
Benefits of:Ø contains a large number of naming and directory services that can be accessed using the same API call for any naming or directory service. Ø multiple naming and directory services can be connected at the same time. Ø allows you to associate a name with a Java object or resource without having to know the physical ID of the object or resource. Ø Access to different kinds of directory services using a common interface ø enables developers to centrally use and implement a type of naming or directory service client API.1.5 JNDIThe structure of the application structure Jndi consists of an API and an SPI, and the Java Application Utility Jndi API accesses a wide variety of naming and directory services.
Figure 14.6 JNDI
Application Structure
1.
JNDI
ContextThe naming service mentioned earlier is associating names with objects. This association is called binding. A set of such bindings is called a context, the JNDI context can be used to find, bundle/unbind, create or break the binding name operation in Jndi, the context is represented using the Javax.naming.Context interface, and this interface is the primary interface that interacts with the naming service. Each named method in the Context interface has two overloaded forms: lookup (string name): Takes a string names parameter to find the bound remote object. Lookup (Javax.naming.Name): Accepts a structured name to find the bound remote object.
2.
Initializing ContextInitialContext is a class that implements the context interface. Use this class as your entry point to the naming service. Creating a InitialContext object constructor takes a set of properties in the form of java.util.Hashtable or one of its subclasses, such as:
code Example 5
Properties Props = new properties ();p rops.setproperty ("Java.naming.factory.initial", " Org.jnp.interfaces.NamingContextFactory ");p rops.setproperty (" Java.naming.provider.url "," localhost:1099 "); Nitialcontext = new InitialContext (props); |
To access resources through jndi , we must set parameters for the initialization context, primarily setting the jndi -driven class name (java.naming.factory.initial) and the URL that provides the naming service ( Java.naming.provider.url). Because the jndi product has many. So the value of java.naming.factory.initial varies by providing a jndi server,java.naming.provider.url values include the host address and port number that provides the naming service. The following table lists the factory classes that are used for the supported service providers. Table : Value of Context.initial_context_factory
Name |
Service Provider Factory |
File system |
Com.sun.jndi.fscontext.RefFSContextFactory |
Ldap |
Com.sun.jndi.ldap.LdapCtxFactory |
Rmi |
Com.sun.jndi.rmi.registry. registrycontextfactory |
Corba |
Com.sun.jndi.cosnaming.CNCtxFactory |
Dns |
Com.sun.jndi.dns.DnsContextFactory |
1.6 RMIIntegration with Jndi through the above Jndi understanding we can use Jndi to manage the registry service for RMI remote objects, and we will rewrite code example 3 as follows:
code Example 6
Package com.itjob.rmi; Import Java.rmi.*;import Java.rmi.registry.*;import javax.naming.*; public class Rmisampleserverjndi{public static void Main (string[] args) throws exception{Locateregistry.createregistry (8808); Rmisampleimpl server=new Rmisampleimpl (); System.setproperty (Context.initial_context_factory, "com.sun.jndi.rmi.registry.RegistryContextFactory"); System.setproperty (Context.provider_url, "rmi://localhost:8808"); InitialContext ctx=new InitialContext (); ctx.bind ("Java:comp/env/sampledemo", server); Ctx.close (); }} |
To start the service-side program:
Figure 14.7 JNDI
Service Program StartupIndicates that the service-side program has registered the remote object in Jndi, waiting for the client to make a call. Next we rewrite the client program to invoke the remote object in a jndi manner
code Example 7
Package Com.itjob.rmi;import java.rmi.*;import java.rmi.server.*;import javax.naming.*;p ublic class Rmisampleclientjndi {public static void main (string[] args) throws Exception{system.setproperty (Context.initial_ Context_factory, "com.sun.jndi.rmi.registry.RegistryContextFactory"); System.setproperty (Context.provider_url, "rmi://localhost:8808"); InitialContext ctx=new InitialContext (); String url = "Java:comp/env/sampledemo"; Rmisample Rmiobject = (rmisample) ctx.lookup (URL); System.out.println ("1 + 2 =" + Rmiobject.sum);}} |
To run the client program:
Figure 14.8
Client Jndi
Program Run ResultsIndicates that the client has successfully invoked the server-side remote object through Jndi.1.7Learn summary Ørmi a method that runs an object on a Java virtual machine that calls an object that is running on another Java Virtual machine: The purpose of RMI is to provide services for remote communication between Java programs. Ørmi programming Ideas N vs. client: Requires some specific code to reference the remote object, and once the client's code has a reference to the remote object, the call on the remote object is no different than the call to the local object method except the speed. N on the server: You must define classes and instantiate the remote objects of the classes, and the code of the servers must be able to enlist the objects and export their methods to the client so that these methods can be called remotely. n the client and server code must either define or be able to access an interface that declares a method that can be called remotely, and both can also set a security manager. n when invoking a method on a remote object, the client can pass the object as a parameter, and the methods on the remote object can return objects, which are implemented by serialization. Øjndi provides developers with a common, unified way to find and access various naming and directory services. The Øjndi structure consists of an API and an SPI, and the Java Application Utility Jndi API accesses a wide variety of naming and directory services.
Java Distributed Processing Technology (RMI,JDNI)