• java RMI 协议通过zookeeper的实现


    ZooKeeper的基本应用_数字公民某杨的博客-CSDN博客

    在上文中,介绍了zookeeper集群的基本应用,通过一个客户端,可以创建zookeeper的子节点,然后通过监听机制获取节点的信息。

    这个功能主要用于分布式服务器之间的功能调用。

    分布式应用,或者说微服务,是把一个功能组合拆分成多个子应用,然后各个子应用各自安装在不同的远程服务器上。这样的话,不同的功能之间有可能需调用其它子应用的功能,尤其是面向前端、客户端的服务器,作为一个用户交互的接口,肯定存在这种远程调用的需求。

    java1.2开始提供一个RMI,remote  method invocation。这个功能可以提供两台服务器之间java实现的功能之间相互调用。结合zookeeper,可以解耦不同功能,实现分布式应用的健壮性、灵活性。

     服务端创建服务对象,然后像http通信一样,把这个服务对象通过bind函数绑定到ip和端口号。然后客户端就通过lookup函数(传入服务端ip和端口号),就可以使用服务端提供的这个对象的功能。

    zookeeper的功能就是服务端的ip和端口号由服务端注册在zookeeper,然后客户端从服务端取。这样就提供了更大的灵活性。

    附:服务端参考代码

    public class ServerDemo implements Watcher {
    public static void main(String[] args) throws IOException,
    AlreadyBoundException, KeeperException, InterruptedException {
    UsersService usersService = new UsersServiceImpl();
    LocateRegistry. createRegistry ( 8888 );
    String url = "rmi://localhost:8888/user" ;
    Naming. bind (url,usersService);
    // url 信息放到 zookeeper 的节点中
    ZooKeeper zooKeeper = new
    ZooKeeper( "192.168.233.130:2181,192.168.233.130:2182,192.168.233.
    130:2183" , 150000 , new ServerDemo());
    // 创建 Znode
    zooKeeper.create( "/service" ,url.getBytes(),
    ZooDefs.Ids. OPEN_ACL_UNSAFE , CreateMode. PERSISTENT );
    System. out .println( " 服务发布成功 " );
    }
    客户端:
    public class ClientDemo implements Watcher {
    public static void main(String[] args) throws IOException,
    KeeperException, InterruptedException, NotBoundException {
    ZooKeeper zooKeeper = new
    ZooKeeper( "192.168.233.130:2181,192.168.233.130:2182,192.168.233.
    130:2183" , 150000 , new ClientDemo());
    byte [] bytes = zooKeeper.getData( "/service" , new
    ClientDemo(), null );
    String url = new String(bytes);
    UsersService usersService = (UsersService)
    Naming. lookup (url);
    String result = usersService.findUsers( "Bj" );
    System. out .println(result);
  • 相关阅读:
    vue3中祖孙组件之间的通信provide和inject
    vscode 配置 Rust 运行环境
    qt-mvvm代码分析
    ubuntu dhcp无法配置路由、setting找不到network问题解决办法
    PMP项目管理实战 | 项目经理如何做好会议管理?
    chatglm2微调—Lora
    大数据学习(10)-Explain详解
    dependencies
    这一题的后缀表达式应该怎样求?
    6 张图告诉你 RocketMQ 是怎么保存偏移量的
  • 原文地址:https://blog.csdn.net/m0_47161778/article/details/126094526