文章目录
RMI定义:(Remote Method Invocation) 远程方法调用,即允许运行在一个JAVA虚拟机的对象调用运行在另一个JAVA虚拟机上的对象的方法。这两个虚拟机可以是在同一台计算机上的不同进程,也可以是运行在网络上的不同计算机。
首先,这种工作模式是基于CS的,即,基于网络的。
客户端:在客户端这些方法只是以接口的方式声明出来,客户端必须提供代理,用代理执行某些方法
服务器端:这些方法本身的具体实现。
RMI的几个特点:
1.需要创建:RMI服务器和RMI客户机
2.服务器和客户机双方持有相同接口
3.为了能让RMI处理“高并发”,就需要用短连接
4.为了能更好的处理高并发,最好使用“线程池”
5.对于客户端的远程连接和调用,应该处理“无效请求”的问题,这里可以使用“模态框”技术。
RMI框架的简单实现:
1.实现由两个部分组成:
*客户端:*提供代理,并且客户端通过代理对象调用那些在服务器端实现的方法,需要将方法执行时所需要的实参数值提供给服务器端。
*服务器端:*需要不停的监控来自客户端的网络接入请求,一旦发现相关请求,立刻连接客户端,获取要执行的方法和方法参数,在服务器端实际执行相关方法,并将相关方法的执行结果通过网络反馈给客户端。
1.实现RMI客户端:
1.1RMIClient:
//进行服务器端的IP和Port的设置
private String rmiServerIp;
private int rmiServerPort;
public RMIClient() {
}
public void setRmiServerIp(String rmiServerIp) {
this.rmiServerIp = rmiServerIp;
}
public void setRmiServerPort(int rmiServerPort) {
this.rmiServerPort = rmiServerPort;
}
String getRmiServerIp() {
return rmiServerIp;
}
int getRmiServerPort() {
return rmiServerPort;
}
1.2RMIProxy:
通过接口,获取代理对象,并返回远程方法调用的结果。
public class RMIProxy {
private RMIClient client;
private IRMIExceptionDealer rmiExceptionDealer;
public RMIProxy() {
this.rmiExceptionDealer = new RMIExceptionDealerAdapter();//使得rmiExceptionDealer无论如何都存在
}
public void setRmiExceptionDealer(IRMIExceptionDealer rmiExceptionDealer) {
this.rmiExceptionDealer = rmiExceptionDealer;
}
public void setClient(RMIClient client) {
this.client = client;
}
@SuppressWarnings("all")
public <T> T getProxy(Class<?> interfase) {
ClassLoader classLoader = interfase.getClassLoader();//获取类加载器
Class<?>[] interfaces = new Class<?>[] {
interfase };//自己创建一个接口数组,并且赋初值
return (T) Proxy.newProxyInstance(classLoader, interfaces, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//Socket socket = null;
if (client == null) {
RMIProxy.this.rmiExceptionDealer.rmiClientNotSetDealer();
return null;
}
RMIClientActioner clientActioner = new RMIClientActioner(method,args,
client.getRmiServerIp(),
client.getRmiServerPort());
clientActioner.doRmi();
return clientActioner.getResult();//返回远程方法调用的结果
}
});
}
@SuppressWarnings("all")
public <T> T getProxy(Class<?> interfase, JFrame owner,String toolTip) {
ClassLoader classLoader = interfase.getClassLoader();//获取类加载器
Class<?>[] interfaces = new Class<?>[] {
interfase };//自己创建一个接口数组,并且赋初值
return (T) Proxy.newProxyInstance(classLoader, interfaces, new InvocationHandler() {
@Override
public Object invoke(