java RMI 原理与编程(分布式对象1)

来源:互联网 发布:c语言调用函数被跳过 编辑:程序博客网 时间:2024/04/20 10:15

要理解RPC首先回顾一下RMI的工作原理

RMIJava提供的Remot Method Invocation

他的工作原理是:首先制定远程调用接口

interface RmotMethods  extends Remot

{

SerialType     Method1…..;

SerialType     Method2 (…….);

…………………………….

}

2.实现Server

/*1.定义实现了RemotMethod Inferface的类:ServeRemot

2.实例化 RmtObj=new  ServeRemot()

3.在Registry中注册RmtObj,得到RmtObj的存根 ServeStub

4.给定ServeStub一个名字name ,将ServeStubname绑定到当地(当前host)的一个分布式对象Registry上。

*/

//1.以上所述第一步

Class ServeRemot  implements  RemotMethods

{

      SerialType Method1(。。。。。)

{

。。。。。。。。。。。。

}

/****

*/

}

Void main()

{//2。第二步

RmtObj=new ServeRemot();

//3

RemotMethods ServeStub = UnicastRemotObject. ExportObjectRmtObj0);

//4

Registy LocalRegistry=LocatRegistry. GetRegistry();

LocalRegistry.rebind(“nameforRmtObj”,ServeStub);

}//main

3.client端的实现

/*任何一个Client端访问Serve都要得到ServeObj的引用Reference。但是ServeClient不再一个主机上,Client怎样得到ServeReference呢?(这个问题很重要在稍后的分布式是对象应用环境的简单实现专题中这一点也是一个关键点)

回答这个问题请注意在Serve端的实现我们将ServeObj在一个Regisry中进行了注册把它和一个name绑定在了一起。Registry是个什么东西? Registry API说明已经很明白了:Registry is a remote interface to a simple remote object registry that provides methods for storing and retrieving remote object references bound with arbitrary string names. The bind, unbind, and rebind methods are used to alter the name bindings in the registry, and the lookup and list methods are used to query the current name bindings

Registry总是由LocatRegisry返回的。那LocatRegisry类又起什么作用了?联系上上一个问题Client端是怎样得到ServeObj的引用的呢?答案已经很明朗了。LocatRegistry调用GetRegistry得到一个Remot host上的特定(如指定的端口)Registry,然后Client查找这个Remot Registy得到RemotObjReference.

以下是摘自LocatRegisryApi说明:

LocateRegistry is used to obtain a reference to a bootstrap remote object registry on a particular host (including the local host), or to create a remote object registry that accepts calls on a specific port.

Note that a getRegistry call does not actually make a connection to the remote host. It simply creates a local reference to the remote registry and will succeed even if no registry is running on the remote host. Therefore, a subsequent method invocation to a remote registry returned as a result of this method may fail.

*/

Client的实现:

String name = "Compute";

Registry registry = LocateRegistry.getRegistry(args[0]);

RemotMethods   ClientObj=(RemotMethods) registry.lookup(name);

/*

对得到的RemotObj的引用ClientObj执行操作

*/

 
原创粉丝点击