zookeeper实现注册中心(demo)

服务端:

public class ZkTest {
   private ZooKeeper zooKeeper;

   public ZkTest() {
      init();
   }

   private void  init(){

      try {
         ResourceBundle bundle = ResourceBundle.getBundle("zk");
         String url=bundle.getString("zk.url");
         Integer time=Integer.valueOf((String) bundle.getString("zk.timeout"));
         zooKeeper= new ZooKeeper(url, time, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
               if(event.getType().equals(Event.EventType.NodeDataChanged)){
                  System.out.println(event.getPath()+"节点发生了改变");
               }
            }

         });
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
   public void createNode() throws KeeperException, InterruptedException {
      String path = zooKeeper.create("/root/server", "服务提供者".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
      System.out.println("添加一个服务提供者:"+path);
   }

   public static void main(String[] args) {
      ZkTest zkServer = new ZkTest();
      try {
         for (int i=0;i<5;i++){
            zkServer.createNode();
         }

         Thread.sleep(Long.MAX_VALUE);
      } catch (KeeperException e) {
         e.printStackTrace();
      } catch (InterruptedException e) {
         e.printStackTrace();
      }
   }



}
消费端:

public static void main(String[] args) throws InterruptedException {
    ZkClient zkClient = new ZkClient(new ZkConnection(CONNECT_ADDR, SESSION_TIMEOUT));
    zkClient.subscribeChildChanges("/root", new IZkChildListener() {
        @Override
        public void handleChildChange(String s, List<String> list) throws Exception {
            System.out.println(s+"的子节点发生改变"+ Arrays.toString(list.toArray()));
        }
    });
    Thread.sleep(Integer.MAX_VALUE);
}

测试:先启动消费端,在启动服务端

服务端生成五个临时节点


消费端获取了服务端的节点


关闭服务端,临时节点会自动删除,消费端会自动监听到


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值