• 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);
  • 相关阅读:
    室内定位:5G定位开启高精度定位新纪元
    腾讯二面——程序崩溃问题连问
    vue video播放m3u8源
    postman设置接口关联这样做,薪资直接涨3k
    Java 网络编程之TCP(二):基于BIO的聊天室
    Stream流reduce方法
    R语言dplyr包filter函数过滤dataframe数据中指定数据列的内容包含指定字符串的数据行、基于grepl函数
    怎么设计个性时尚的班服?一起来看看莱佛士学生的设计
    使用dockerfile部署springboot应用
    甲方不让用开源【监控软件】?大不了我自己写一个
  • 原文地址:https://blog.csdn.net/m0_47161778/article/details/126094526