要理解RPC首先回顾一下RMI的工作原理 :
RMI是Java提供的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 ,将ServeStub和name绑定到当地(当前host)的一个分布式对象Registry上。
*/
//1.以上所述第一步
Class ServeRemot implements RemotMethods
{
SerialType Method1(。。。。。)
{
。。。。。。。。。。。。
}
/****
*/
}
Void main()
{//2。第二步
RmtObj=new ServeRemot();
//3
RemotMethods ServeStub = UnicastRemotObject. ExportObject(RmtObj,0);
//4
Registy LocalRegistry=LocatRegistry. GetRegistry();
LocalRegistry.rebind(“nameforRmtObj”,ServeStub);
}//main
3.client端的实现
/*任何一个Client端访问Serve都要得到ServeObj的引用Reference。但是Serve和Client不再一个主机上,Client怎样得到Serve的Reference呢?(这个问题很重要在稍后的分布式是对象应用环境的简单实现专题中这一点也是一个关键点)
回答这个问题请注意在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得到RemotObj的Reference.
以下是摘自LocatRegisry的Api说明:
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执行操作
*/
本文详细介绍了Java远程方法调用(RMI)的工作原理,包括定义远程接口、实现服务器端和服务注册流程,并解释了客户端如何通过查找远程注册表来获取服务引用。
220

被折叠的 条评论
为什么被折叠?



