zoukankan      html  css  js  c++  java
  • 远程服务调用RMI框架 演示,和底层原理解析

    远程服务调用RMI框架: 是纯java写的, 只支持java服务之间的远程调用,很简单,

      // 接口要继承 Remote接口
    public interface IHelloService extends Remote {
    
        public String sayHello(String msg)throws RemoteException;
    }
    
    
    
    //实现类 要继承 UnicastRemoteObject 类, 并重写 构造方法
    public class HelloServiceImpl extends UnicastRemoteObject implements IHelloService {
        protected HelloServiceImpl() throws RemoteException {
            super();
        }
    
        @Override
        public String sayHello(String msg) throws RemoteException{
            return "hello "+msg;
        }
    }
    
    
      ## 发布服务
    public class RMI_Server {
        public static void main(String[] args) throws Exception {
            //这是将 本服务发布出去
            IHelloService helloService = new HelloServiceImpl();
            //这是将 locateRegistry 相当于注册中心, 发布出去
            LocateRegistry.createRegistry(1099);
            //这是将 rul 和 服务,存到 HashTable中, 并发布出去
            Naming.bind("rmi://127.0.0.1/hello",helloService);
    
            System.out.println("服务发布成功");
        }
    }
    
    
     ## 服务调用client
    public class RMI_Client {
        public static void main(String[] args) throws RemoteException, NotBoundException, MalformedURLException {
            IHelloService helloService = (IHelloService) Naming.lookup("rmi://127.0.0.1/hello");
            System.out.println(helloService.sayHello("啦啦啦啦啊"));
        }
    }
    

    运行结果:

    源码解读: 这里参考别人博客,自己不重复造轮子:
    https://blog.csdn.net/qq_20597727/article/details/80861906

    自己理解:
    HelloServiceImpl ---> 构造-->exportObject(obj, new UnicastServerRef(port));--->1:这里先对当前对象代理生成代理对象, 将代理对象包装成Target对象,发布出去--->TCPEndPoint发布服务(可以将这里看做传输层) ---> this.listen(); 监听( 这里面可看到 工厂模式 new 了一个 serverSocket, 并创建一个线程 (这个线程循环 socket阻塞, 当监听到client过来的时候, 线程池调用线程,发送,当前服务对象, 最后关闭 serverSocket) )

    LocateRegistry.createRegistry(1099); ------>this.setup(new UnicastServerRef(var2, RegistryImpl::registryFilter));----->var1.exportObject(this, (Object)null, true);----> 接下来和 发布服务是一样的... 这个操作是将LocateRegistry 发布出去, LocateRegistry相当于注册中心,是单独的一个进程,在 java/bin下

    Naming.bind("rmi://127.0.0.1/hello",helloService); -----> 这个是将url 和对应服务 绑定起来,---> 先获取这侧表, 然后注册表将 url 和 对应服务绑定 内部其实是一个Hashtable , url---key, 服务--->value , 获取一个新连接, 将 url和服务 发送出去

    Client 端, IHelloService helloService = (IHelloService) Naming.lookup("rmi://127.0.0.1/hello"); --->先获取到注册表, 然后监听 对应的 rul, 先从HashTable中根据url 获取服务,有就直接返回

  • 相关阅读:
    类型转换
    希尔排序
    冒泡排序
    More Effective C++ (静态绑定与动态类型)
    More Effective C++ (限制类的对象数量)
    算法复杂度
    交换两个数的方法
    QString类(常用函数)
    面向过程与面向对象
    QTableWidget控件总结
  • 原文地址:https://www.cnblogs.com/lvcai/p/13672920.html
Copyright © 2011-2022 走看看