Вы находитесь на странице: 1из 18

Java-RMI Introduction

The Java RMI is Javas native scheme for creating and using remote objects. Java RMI provides the following elements: 1. Remote object implementations. . !lient interfaces" or stubs" to remote objects. #. $ remote object registr% for finding objects on the networ&. '. $ networ& protocol for communication between remote objects and their client (this protocol is JRM)" i.e. Java Remote Method )rotocol*. +. $ facilit% for automaticall% creating (activating* remote objects on,demand.

-ach of these elements (e.cept the last one* has a Java interface defined for it in the java.rmi pac&age and its subclasses. RMI is part of the core Java $)I and has been enhanced for J/0 1. (Java platform* in recognition of the critical need for support for distributed objects in distributed,application development.

1ith RMI" %ou can get a reference to an object that 2lives3 in a remote process on remote hosts and invo&e methods on it as if it were a local object running within the same Java virtual machine as %our code. -ach remote object implements a remote interface that specifies which of its methods can be invo&ed b% clients.

)rior to RMI" a distributed application involved soc&et programming" where a raw communication channel was used to pass messages and data between two remote processes. The programmer needed to define a low,level message protocol and data transmission format between processes in the distributed application.

1ith RMI" %ou can 2e.port3 an object as a remote object" so that other remote processes4agents can access it directl% as a Java object. RMI handles all the underl%ing networ&ing needed to ma&e %our remote method calls wor&. RMI is a Java,onl% distributed object scheme5 the distributed objects in an RMI,based distributed application have to be implemented in Java. This could be a problem when interfacing with legac% applications. !6R7$" on the other hand" is a language,independent distributed object scheme. It is however" more comple. to wor& with than RMI.

Advantages of RMI

8ince RMI is a Java native" integration of its remote object facilities into a Java application is seamless. 9ou can use RMI,enabled objects as if the% live in the local Java environment. RMI e.tends the internal garbage,collection mechanisms of the standard J:M to provide distributed garbage collection of remotel% e.ported objects.

RMI is platform,independent (though not language, independent*. RMI is eas% to learn. 9ou can migrate entire objects (i.e. class b%te codes are portable* to a remote host via object seriali;ation in RMI. This is not possible in !6R7$.

Your options, if you have a distributed application with heterogeneous components, some of which are written in Java and some that are not:

9ou can use !6R7$ since it is supports language, independent object interfaces (the Java IDL API included in the Java platform covers the Java interface to !6R7$*. 9ou can use RMI" wrapping the non,Java code with RMI,enabled Java objects using the Java <ative Interface (J<I*. The third option involves the new RMI4II6) functionalit% that allows RMI objects to communicate directl% with remote !6R7$ objects over II6) (Internet Inter,6rb )rotocol*.

RMI Architecture
!lient objects 8tub Remote reference la%er RMI Transport la%er
!hysical path ogical !ath

8erver 6bjects 8&eleton Remote reference la%er RMI Transport la%er

The RMI runtime architecture There are three la%ers that comprise the basic remote,object communication facilities in RMI: 1. The stub/skeleton la%er" which provides the interface that client and server application objects use to interact with each other. . The remote reference la%er" which is the middleware between the stub4s&eleton la%er and the underl%ing transport protocol. #. The transport protocol la%er" which is the binar% data protocol that sends remote object re=uests over the wire.
In the figure" the server is the application that provides remotel% accessible objects" while the client is an% remote application that communicates with these server objects.

/escription of the architecture: 1. The client uses the client,side stub to ma&e a re=uest of the remote object. The server object receives this re=uest from a server,side object s&eleton. . $ client initiates an RMI invocation b% calling a method on a stub object. The stub maintains an internal reference to the remote object it represents and forwards the method invocation re=uest through the remote reference la%er b% marshaling the method arguments into seriali;ed form and as&ing the remote

#.

'. +.

>. ?.

@. A.

reference la%er to forward the method re=uest and arguments to the appropriate remote object. Marshaling involves converting local objects into portable form so that the% can be transmitted to a remote process. -ach object (e.g. a 8tring object" an arra% object" or a user defined object* is chec&ed as it is marshaled" to determine whether it implements the java.rmi.Remote interface. If it does" its remote reference is used as its marshaled data. If it isnt a Remote object but is rather a Seriali able object" the object is seriali;ed into b%tes that are sent to the remote host and reconstructed into a cop% of the local object. If the object is neither Remote nor 8eriali;able" the stub throws a java.rmi.!arshal"#ception bac& to the client. If the marshaling of method arguments succeeds" the client,side remote reference la%er receives the remote reference and marshaled arguments from the stub. The remote reference la%er converts the client re=uest into low,level RMI transport re=uests" i.e." into a single networ&,level re=uest and sends it over the wire to the sole remote object (since in Java the communication st%le supported is the point,to,point object references* that corresponds to the remote reference passed along with the re=uest. 6n the server" the server,side remote reference la%er receives the transport, level re=uest and converts it into a re=uest for the server s&eleton that matches the referenced object. The s&eleton converts the remote re=uest into the appropriate method call on the actual server object. This involves unmarshaling the method arguments into the server environment and passing them to the server object. $rguments sent as remote references are converted into local stubs on the server" and arguments sent as seriali;ed objects are converted into local copies of the originals. If the method calls generates a return value or an e.ception" the s&eleton marshals the object for transport bac& to the client and forwards it through the server reference la%er. The result is sent bac& using the appropriate transport protocol (e.g. 8oc&et $)I using T!)4I)*" where it passes through the client reference la%er and stub" is unmarshaled b% the stub" and is finall% handed bac& to the client thread that invo&ed the remote method.

RMI "b#ect $ervices

RMI provides some basic object services on top of its remote object architecture that can be used b% the distributed application designer. These services are: 1. <aming4Registr% 8ervice
$ server process needs to register one (or more* RMI,enabled objects with its local RMI registr% (represented b% the Registr$ interface* using a name that clients can use to reference it. $ client can obtain a stub reference to the remote object b% as&ing for the object b% name through the %aming interface. The %aming.lookup&' method ta&es the name of a remote object and locates the object on the networ&. The objects name is in a BRC,li&e s%nta. that includes the name of the objects host and the objects registered name. 6nce the lookup&' method locates the objects host" it consults the RMI registr% on the host and as&s for the object b% name. If the registr% finds the object" it generates a remote reference to the object and delivers it to the client process" where it is converted into a stub (local* reference that is returned to the caller.

. /istributed Darbage !ollection

This is an automatic process that the application developer does not have to worr% about.
/escription: -ver% server that contains RMI,e.ported objects automaticall% maintains a list of remote references to the objects it serves. -ach client that re=uests and receives a reference to a remote object is issued this remote reference through the remote reference la%er of the objects host process. The reference la%er automaticall% &eeps a record of this reference in the form of an e.pirable lease on the object. 1hen the client is done with the reference it allows the remote stub to go out of scope and notifies the server that it is done with the reference to the object. Then the reference la%er on the server automaticall% deletes the record of the remote reference and informs the clients reference la%er that this remote reference has e.pired. 8hould the lease on the object e.pire then the reference

la%er on the server also deletes the record of the remote reference. This is used to deal with situations when a client or networ& failure prevents a client from notif%ing the server that it is done with its reference to an object. 1hen an object has no further remote references recorded in the remote reference la%er" it becomes a candidate for garbage collection. If there are also no local references to the object then this object is pic&ed up the garbage collector in the ne.t run of the s%stem garbage collector.

#. 6bject $ctivation 8ervice This service is new to RMI as of version 1. of the Java platform. It provides a wa% for a server object to be activated automaticall% when a client re=uests it.
1ithout remote activation" a server object has to be registered with the RMI registr% service from within a running J:M. If the server :M crashes" the server object becomes unavailable and an% e.isting client references to the object are lost. 1ith remote activation" a server object can be created within a new or e.isting :M and a reference to this newl% created object can be obtained for the client that caused the activation. $ server object that wants to be activated automaticall% needs to register an activation method with the RMI activation daemon (rmid* running on its host.

%efining Remote "b#ects /efining a remote RMI object involves specif%ing a remote interface for the object" then providing a class that implements this interface. The remote interface and implementation class are then used b% RMI to generate a client stub and server s&eleton for %our remote object. The communication between local objects and remote objects is handled using these stubs and s&eletons. The RMI compiler (rmic* automaticall% generates the stub and s&eleton classes based on the remote interface and implementation classes provided b% %ou. e.g. rmic 9our8erverImpl

The stub and s&eleton classes act as go,betweens for the client application and the actual server object. Eor the client stub class" the rmic compiler generates an implementation of each remote method that pac&ages (marshals* the method arguments and transmits them to the server. Eor the server s&eleton class" the RMI compiler generates another set of implementations of the remote methods" but these are designed to receive the method arguments from the remote method call" unpac&age them" and ma&e the corresponding call on the object implementation. 1hatever the method call generates (return data or an e.ception*" the results are pac&aged and transmitted bac& to the remote client. The client stub method (which is still e.ecuting (s%nchronous call* at this point* unpac&ages the results and delivers them to the client as the result of its remote method call.

-ver% object %ou want to distribute using RMI has to e.tend the java.rmi.Remote interface. -ver% method in the remote interface has to declare that it throws a java.rmi.Remote"#ception or one of the parent classes of Remote"#ception.
The first re=uirement allows RMI to tag remote objects as such and to differentiate between objects that are remote and those that are not. The second re=uirement is needed to deal with errors that can happen during a remote session. 8uch errors include: client,side error (an argument cant be marshaled*" errors during transport of data between client and server (networ& connection is lost*" errors on the server side (the method throws a local e.ception that needs to be sent bac& to the remote caller*. The Remote"#ception class is used b% RMI as a base e.ception class for an% of the different t%pes of problems that might occur during a remote method call. $n% method declared in a Remote interface is assumed to remotel% callable" so ever% method has to declare that it might throw a Remote"#ception. <ote: the implementation class of %our Remote interface can include other methods that are not remotel% callable. These methods do not have to be declared as throwing a Remote"#ception.

-.ample
import #ava&rmi&Remote' import #ava&rmi&Remote()ception' public interface Your$erver e)tends Remote * public $tring do+his,$tring todo- throws Remote()ception' public $tring do+hat,$tring todo- throws Remote()ception' .

RMI /lasses for Remote "b#ect Implementations -.ample of an implementation of a Remote class:
import #ava&rmi&server&0nicastRemote"b#ect' import #ava&rmi&Remote()ception' public class Your$erverImpl e)tends 0nicastRemote"b#ect implements Your$erver * 11constructor public Your$erver Impl,- throws Remote()ception * . 11remotely accessible methods public $tring do+his,$tring todo- throws Remote()ception * return do$omething,2this3, todo-' . public $tring do+hat,$tring todo- throws Remote()ception * return do$omething,2that3, todo-' . 11non-remote method private $tring do$omething,$tring what, $tring todo- * $tring result 4 what 5 todo 5 2&3' . .

The (ourServerImpl class e.tends the UnicastRemoteObject class. This is a class in the java.rmi.server pac&age that e.tends the java.rmi.server.RemoteServer" which itself e.tends java.rmi.server.Remote)bject" the base class for all RMI objects. Remote6bject

Remote)bject is an abstract class that implements the e*uals&'+ toString&'+ etc." methods inherited from 6bject in a wa% that ma&es sense for remote objects. The e*uals&' method" for e.ample" is implemented to return true if the internal remote references of the two Remote)bject objects are e=ual (i.e. the% both point to the same server object*.

Remote8erver
RemoteServer is an abstract class that e.tends Remote)bject. It acts as a base class for classes that define various semantics for remote objects" e.g. point,to,point reference scheme" or a scheme where there are multiple copies of an object scattered

across a networ& etc. $t present" onl% point,to,point" non,persistent remote references are supported b% the ,nicastRemote)bject class" which is a subclass of RemoteServer.

BnicastRemote6bject
This is a concrete subclass of RemoteServer that implements point,to,point remote references over T!)4I) networ&s. These references are nonpersistent: remote references to a server object are onl% valid during the lifetime of the server object. If the :M containing the object e.its" an% e.isting remote references on clients become invalid and generate Remote"#ception objects if used.

$ctivatable
This concrete subclass of RemoteServer is part of the new RMI object activation facilit% in Java 1. and can be found in the java.rmi.activation pac&age. If a remote method re=uest is received on the server host for an Activatable object" and the target object is not e.ecuting at that time" the object can be started automaticall% b% the RMI activation daemon.

!reating 8tubs and 8&eletons The RMI compiler (rmic* generates the stub and s&eleton. The command is:
rmic Your$erverImpl

The command
rmic 6d 1usr1local1classes Your$erverImpl

generates stub and s&eleton classes in the specified director%. Registr% and <aming 8ervices The principal use for the Registr$ and %aming classes in an RMI application is as a means to bootstrap %our distributed applications. $ server process e.ports its objects through its local RMI registr% daemon. !lients loo& up these objects through the %aming facilit% to get remote references to them. Java provides an RMI registr% daemon" rmiregistr$. This utilit% creates a Registr% object that listens to a specified port and then goes into a wait loop" waiting for local processes to register objects with it or for clients to connect and loo&up RMI objects in its registr%. The command is:
rmiregistry 7888 9

1ithout the port argument" the RMI registr% listens on port 1FAA. The rebin-&' method of the java.rmi.%aming interface is used to register an object with a name in the local registr%" where the name for an object can be an% uni=ue string. 9ou can remove the object binding using the unbin-&' method. <ote: the rebind(*" and unbind(* methods can onl% be called b% clients running on the same host as the registr%" else a java.rmi.Access"#ception is received b% the client. 9ou can loo&up a particular object in the registr% using the lookup&' method" while list&' returns the names of all the objects registered with the local registr%. 6nl% Remote objects can be bound to a name in the Registr$ since onl% the% are capable of supporting remote references. -.ample of registering an object:
import #ava&rmi&:aming' try * Your$erverImpl serv 4 new Your$erverImpl,-' :aming&rebind,;Johnserver;, serv-' . catch,()ception e- * e&print$tac<+race,-' .

The <aming class lets a client loo& up local and remote objects using an BRC,li&e naming s%nta.. The format of this BRC is: rmi:44objhost.org:1FAA4obj<ame where objhost.org is the host of the object" 1FAA is the registr% port" and obj<ame is the registered name of the object. -.ample of loo&ing up an object"
import #ava&rmi&:aming'
try *

Your$erver rmtserver 4 ,Your$erver-:aming&loo<up,2rmi:11osprey&unf&edu1Johnserver3-'

. catch,()ception e- * e&print$tac<+race,-' .

If %ou have a client running on the same host as 9our8erverImpl object" the loo&up command is:
Your$erver rmt$erver 4 ,Your$erver-:aming&loo<up,2Johnserver3-'

$lternativel%" %ou can use the LocateRegistr$ and Registr$ interfaces to loo& up the same object as in:
Registry rmtRegistry 4 ocateRegistry&getRegistry,2osprey&unf&edu3-' Your$erver rmt$erver 4 ,Your$erver- rmtRegistry&loo<up,2Johnserver3-' <ote: The <aming.loo&up(* method internall% ma&es the same two calls listed above.

Mechanisms used to pass arguments and return results from remote methods: This depends on the t%pe of data being passed. Primitive t$pes (int" boolean" double etc.* are passed b% value" just as in a local Java method invocation. If the object is a Remote object" a remote reference for the object is generated" and the reference is marshaled and sent to the remote process.
The remote reference is received on the other end and converted into a stub for the original object. This process applies to both the method arguments and return values.

If the object is Seriali able but not Remote" the object is seriali;ed and streamed to the remote process in b%te form. The receiver converts the b%tes into a cop% of the original object. If the method argument or return value is not seriali;able (i.e." its not a primitive data t%pe or an object that

implements Seriali able*" the object cant be sent to the remote client" and a java.rmi.!arshal"#ception is thrown. Eactor% !lasses 1hen a reference to a remote object is obtained through the RMI registr% and then used to re=uest additional remote references" the registered remote object is referred to as a factor$ class. Bsing remote references obtained through method calls on factor% objects" client applications can d%namicall% re=uest the creation of new remote objects" without the objects being registered individuall% with the server registr%.
-.ample 8a% were building a remote ban&ing s%stem using the Account object. The server provides services to remote clients running on )!s" embedded in $TMs etc. 6n the server" we could run an RMI registr%" create an Account object for ever% account we have on record" and register each one with the RMI registr% using the account name. Registry local 4 ocateRegistry&getRegistry,-' local&bind,2Abrams, John3, new AccountImpl,2John Abrams3--' local&bind,2Adams, John3, new AccountImpl,2John Adams3--' : : This is unwield%. 8tarting the server can ta&e long" as thousands of accounts need to be registered" man% of them unnecessaril%" since man% accounts ma% not see an% activit% before the ne.t down time. $lso" accounts that are created or closed during the servers lifetime need to be added or removed from the RMI registr%" as well as from the ban&s database of accounts. 8o we define a factor% class for Account objects" as in: import #ava&rmi&Remote' import #ava&rmi&Remote()ception' public interface AccountManager e)tends Remote * public Account getAccount,$tring name- throws Remote()ception' public =oolean newAccount,Account s- throws Remote()ception' . The Account!anager lets a client as& for an account b% name" using the getAccount&' remote method. The method returns a reference to an Account object that corresponds to the account. 6nce the client has an Account reference" transactions against the account can be done through method calls on the Account object. The $ccountManager also has a ne.Account&' method that allows clients to add new accounts to the underl%ing database.

The server implementation of the getAccount&' method simpl% needs to loo& up the named account in the database" create an AccountImpl object to represent the account" and return the object to the client as a remote reference. 8ince Account objects are Remote objects" the RMI remote reference la%er automaticall% creates a remote reference for the Account object" and the client that called the getAccount&' method receives a stub for the Account object (thus the $ccount object is created on the server but is not registered with the registr% and nor does the client need to call %aming.lookup&' to loo& this object up. This avoids &eeping the RMI registr% in s%nc with the database and an unnecessar% shadow of the database. 6nl% the Account!anager object is registered with the registr% and the client would onl% need to call %aming.lookup&' to get a remote reference to the Account!anager object.* The Account!anager object can access the ban&s database directl% to find accounts and create corresponding Account remote objects.

/%namicall% Coaded !lasses The RMI runtime s%stem provides its own d%namic class loader" the R!I/lassLoa-er" to load stubs and s&eletons for remote interfaces" as well as the classes for objects used as arguments of remote methods or return values.
$ client needs the interface class for the remote object and its stub class. 6n the server side" the s<eleton class for the remote object and the implementation class" need to be loaded in order to run the server object that is being remotel% e.ported. Eirst the default local class loader tries to find the referenced class locall% (e.g. the stub class* in the local !C$88)$TG. If it cant find it locall%" then the R!I/lassLoa-er tries to load the class b%tes remotel%. 1hen the RMI runtime s%stem marshals a remote object stub" method argument" or return value" it encodes a BRC in the marshaled b%testream to tell the process on the receiving end of the stream where to loo& for the class file for the marshaled object.

The value of the java.rmi.server.co-ebase propert% for the J:M marshaling the object is sent in the marshaled b%te stream. To set the propert%:
#ava 6%#ava&rmi&server&codebase4http:11ob#host&org1classes1 RMI!rocess

$n% remote process that needs to load classes for objects received from this process during an RMI session uses this GTT) BRC in order to find them if the classes cant be found on the local !C$88)$TG.

This applies either if RMI)rocess is serving remote objects itself through an RMI registr% if RMI)rocess is passing objects into methods it is calling on other remote objects.

The RMI!lassCoader ta&es the BRC in the marshaled b%testream and opens a BRC connection to the specified host to load the needed classes. If both the local class search and this remote BRC search fail to find the re=uired classes" the unmarshal operation generates an e.ception" and the remote method call fails.

In order for a Java runtime s%stem to even attempt to load classes remotel%" it has to have a securit% manager installed that allows remote class loading. The
java.rmi.RMISecurityManager

is used for this. In both %our RMI object server and clients" include the following line before an% RMI calls:
$ystem&set$ecurityManager,new RMI$ecurityManager,--'

The default Java securit% polic% does not allow all the networ&ing operations re=uired to resolve a class from a remote host. 9ou will need to use a polic% file that opens up networ& permissions to allow this. $ sample polic% file (called m$polic$.t#t* might contain the following:
permission #ava&net&$oc<et!ermission 2ob#host&org3, 2accept,connect3 This gives the RMI object server objhost.org the permission to open connections to the local machine.

<e.t" specif% the polic% file on the command line when %ou start %our RMI process as in:
#ava 6%#ava&security&policy4mypolicy&t)t RMI!rocess

Interfacing with legac% applications 1. RMI and <ative Method calls


7% using Javas <ative Interface $)I" it is possible to wrap e.isting ! or !HH code with a Java interface and then e.port this interface remotel% through RMI. $dvantage: 9oure running Java at both ends of the remote communication and avoiding use of !6R7$" which ma% be over&ill for %our application. Bsing the simpler RMI ma% be an advantage.

. !6R7$

$ !6R7$ object implemented in the same language as the native code (!4!HH* is created and e.ported on the server. Remote Java clients can get a Java stub to this !6R7$ object using JavaI/C.
$dvantage: %ou dont need Java on the server. 8ince this is presumabl% a mainframe" finding a stable J:M and development &it for the platform ma% be a problem. If a Java implementation isnt available or if installing additional software on the legac% server isnt desirable" !6R7$ is %our onl% option.

#. RMI over II6) RMI objects can communicate directl% with !6R7$ objects using II6)" the !6R7$ networ& interface protocol. This means that an RMI object using RMI4II6) can communicate with a remote !6R7$ object" regardless of the implementation language of the !6R7$ object and the !6R7$ object can interact with %our Java RMI objects directl%.

"b#ect $eriali>ation To cop% an object" %ou need to convert it into a stream of b%tes. 6bject seriali;ation is a scheme that converts objects into a b%te stream that is passed to other machines5 these rebuild the original object from the b%tes. $n object %ou want to seriali;e must implement the java.io.Seriali able interface. In RMI" seriali;ation is used to marshal4unmarshal method arguments that are objects" but that are not remote objects. $n% object argument to a method on a remote object in RMI must implement the Seriali able interface.

Вам также может понравиться