简述对RPC、RMI的理解

  • RPC:在本地调用远程的函数,远程过程调用,可以跨语言实现 httpClient
  • RMI:远程方法调用,Java中用于实现RPC的一种机制,RPC的Java版本,是J2EE的网络调用机制,跨 JVM调用对象的方法,面向对象的思维方式 直接或间接实现接口 java.rmi.Remote 成为存在于服务器端的远程对象,供客户端访问并提供一定的 服务 远程对象必须实现java.rmi.server.UniCastRemoteObject类,这样才能保证客户端访问获得远程对象 时,该远程对象将会把自身的一个拷贝以Socket的形式传输给客户端,此时客户端所获得的这个拷贝称 为“存根”,而服务器端本身已存在的远程对象则称之为“骨架”。其实此时的存根是客户端的一个代理, 用于与服务器端的通信,而骨架也可认为是服务器端的一个代理,用于接收客户端的请求之后调用远程 方法来响应客户端的请求。
图片[1]-简述对RPC、RMI的理解-不念博客

代码如下:

public interface IService extends Remote {
    String service(String content) throws RemoteException;
}

public class ServiceImpl extends UnicastRemoteObject implements IService {
    private String name;

    public ServiceImpl(String name) throws RemoteException {
        this.name = name;
    }

    @Override
    public String service(String content) {
        return "server >> " + content;
    }
}

public class Server {
    public static void main(String[] args) {
        try {
            IService service02 = new ServiceImpl("service02");
            Context namingContext = new InitialContext();
            namingContext.rebind("rmi://127.0.0.1/service02", service02);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("000000!");
    }
}

public class Client {
    public static void main(String[] args) {
        String url = "rmi://127.0.0.1/";
        try {
            Context namingContext = new InitialContext();
            IService service02 = (IService) namingContext.lookup(url +
                    "service02");
            Class stubClass = service02.getClass();
            System.out.println(service02 + " is " + stubClass.getName());
//com.sun.proxy.$Proxy0
            Class[] interfaces = stubClass.getInterfaces();
            for (Class c : interfaces) {
                System.out.println("implement" + c.getName() + " interface");
            }
            System.out.println(service02.service("hello"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
© 版权声明
THE END
喜欢就支持一下吧
点赞88赞赏 分享
评论 抢沙发
头像
欢迎光临不念博客,留下您的想法和建议,祝您有愉快的一天~
提交
头像

昵称

取消
昵称

    暂无评论内容