zookeeper实现注册中心(demo)

来源:互联网 发布:哈尔滨软件开发88087 编辑:程序博客网 时间:2024/06/01 01:33

服务端:

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);}

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

服务端生成五个临时节点


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


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


原创粉丝点击