1:代理模式定义:它为另一个对象提供一个替身或占位符以控制对这个对象的访问。(通俗解释:在被访问对象前段增加控制类)
2、RMI提供了客户辅助对象和服务端辅助对象,为客户辅助对象创建和服务对象相同方法。
啥也不说了,直接上列子代码:
A:建立远程服务端接口类:
import java.rmi.*; // 引用Java中RMI类
public interface TestServiceRemoteInt extends Remote{
public String sayHello() throws RemoteException; // 远程方法调用必修声明RemoteException异常
}
B:建立远程服务实现类:
import java.rmi.*;
import java.rmi.server.*;
/**
* UnicastRemoteObject为java.rmi.*提供类
*
*
**/
public class TestServiceRmoteImpl extends UnicastRemoteObject implements TestServiceRemoteInt
{
public String sayHello() {
return "Server say Hello";
}
public TestServiceRmoteImpl() throws RemoteException{}
public static void main(String[] args) {
try {
TestServiceRemoteInt TestService = new TestServiceRmoteImpl();
// Naming.rebind(java.rmi.*)方法(为)绑定对象到rmiregistzy中,客户端将使用注册名RemoteHello在Rmiregistzy查找
Naming.rebind("RemoteHello",TestService)
} catch (Exception ex){
ex.printStackTrace();
}
}
}
C:客户端实现访问:
import java.rmi.*;
public class TestClient{
public static void main(String[] args) {
new TestClient().doTest();
}
Public void doTest(){
try{
// rmi://127.0.0.1/RemoteHello格式必修rmi://地址/服务定义名,其中地址可以更换
TestServiceRemoteInt testInter = (TestServiceRemoteInt)Naming.lookup(rmi://127.0.0.1/RemoteHello);
String Say = testInter.sayHello();
System.out.println(s);
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
通过上述简单示例:客户端对象通过RMI代理类(RMI Stub )访问 服务器端代理类(RMI skeleton)再访问服务器对象。