对于MapReduce我已经看完有一段时间了,一直没有写这个后续是觉得对于这个自己还是理解的不太深,不敢随便的就写了,误人子弟,我今天把这个写出来也不是说对于RPC中使用的动态代理的理念有多深的理解的,只是基于自己对项目的理解,然后写出来,和大家分享一下自己的想法,希望有什么理解不到位的,一起探讨。
RPC是java中实现服务之间通信而提出来的,是RMI的一种吧,服务之间的通信有很多种,我这里就不详细的说了。我直接说一下RPC,它是对java应用程序,不同的JVM,而实现的远程过程调用,最主要的是JVM不同,我相信了解JVM的都知道这是什么意思。那么RPC实现的原理是什么呢?我们能想到的是这样的,要想两个服务之间通信,首先想到的是Socket,而我们通信的是Java对象,所以要序列化。然而我们要想使对象在服务器端也像在client一样,因为JVM不一样了,是不是要把类也要传送过去?那这样太麻烦了,我们想到了面向接口编程,我们只需要有接口就好了,那么怎么调用呢?我们想到了动态代理,而且是面向接口的,这是我在理解RPC时,自己能想到的。我想应该也是差不多了。那么具体动态代理的原理我下面给出示例程序,我相信大家很简单的就会看明白是怎么一回事了啊。
public interface ChinaMobile {
void regist();
}
public class ChinaMobileImp implements ChinaMobile {
@Override
public void regist() {
System.out.println("success...");
}
}
public class ChinaMobileAgent implements InvocationHandler {
private ChinaMobile chinaMobile;
public ChinaMobileAgent(ChinaMobile chinaMobile) {
this.chinaMobile = chinaMobile;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
System.out.println("proxy success....");
return method.invoke(chinaMobile, args);
}
}
public class test {
public static void main(String[] args) {
ChinaMobile ch = new ChinaMobileImp();
ChinaMobileAgent agent = new ChinaMobileAgent(ch);
ChinaMobile proxy = (ChinaMobile)Proxy.newProxyInstance(ch.getClass().getClassLoader(), ch.getClass().getInterfaces(), agent);
proxy.regist();
}
}
以上就是我对RPC中使用动态代理的理解有什么理解不到位的,希望批评指正。