[Demo示例]使用curator监听zookeeper

引入依赖

		<dependency>
			<groupId>org.apache.curator</groupId>
			<artifactId>curator-recipes</artifactId>
			<version>2.7.1</version>
		</dependency>

连接

String ADDRESS = "192.168.1.200:2181";
CuratorFramework client = CuratorFrameworkFactory.newClient(ADDRESS, new RetryNTimes(10, 5000));
client.start();

基本命令
curator使用Builder模式,先获取对应ls getData getChildren create delete等命令对应的Builder接口,然后在调用forPath指定位置,或者设置监听。

// 获取一个节点的内容
byte[] d = client.getData().forPath("/lw/1");
System.out.println(new String(d));

监听
curator的监听有三种:

1.NodeCache 监听一个节点,子节点也不关心

NodeCache cache = new NodeCache(client, "/lw/12");
cache.getListenable().addListener(() -> {
	System.out.println("--------------");
});
cache.start();

2.PathChildrenCache 监听一个节点和其子节点,孙子节点不监听

PathChildrenCache pathChildrenCache = new PathChildrenCache(client, "/lw", true);
pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
    @Override
    public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent event) throws Exception {
        System.out.println(event.getType().name());
    }
});
pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);

3.TreeCache 监听所以子孙节点

TreeCache tree = new TreeCache(client, "/lw");
tree.getListenable().addListener((c, event) -> {
	System.out.println(event.getType().name());
});
tree.start();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值