apache原生的zookeeper不太友好,现在市面上有两种,一种是zkclient,在一中就是apache的curator,
相比于zkclient来说,curator文档更友好,提供了Fluent风格的API,更加易懂易操作
首先是创建zk连接
CuratorFramework client = builder.connectString("192.168.11.56:2180") //ip:port
.sessionTimeoutMs(30000) //session timeouot
.connectionTimeoutMs(30000) //connect timeout
.canBeReadOnly(false)
.retryPolicy(new ExponentialBackoffRetry(1000, 3)) //重试策略
.namespace(namespace) //命名空间
.build();
if(!client.isStart())
client.start();
创建节点:
if(client.checkExists().forPath(path) == null)
client.create().forPath(path, value.toBytes);
创建节点的时候还有临时节点,临时有序节点,永久有序节点,采用withMode(CreateMode.),CreateMode提供了集中实现
如果不判断的话,在节点存在的时候会抛出NodeExistsException
判断节点是否存在
Stat stat = client.checkExists().forPath(path);
stat类里面包含了很多信息,包括version,zxid,等信息,zk里面每次更新都会更新一次版本,采用乐观锁的策略,zxid是事务的id(zk里面,事务id采用64位,前32位表示了leader的统治期,后32位表示了事务的序号)
更新数据
if(client.checkExists().forPath(path) != null)
client.setData().forPath(path, value.toBytes);
如果不判断的话,在节点存在的时候会抛出NodeExistsException
删除数据:
if(client.checkExists().forPath(path) != null)
client.delete().forPath(path);
如果不判断的话,在节点存在的时候会抛出NoNodeException
获取子节点:
if(client.checkExists().forPath(path) != null)
List<String> childList = client.getChildren().forPath(path);
如果不判断的话,在节点存在的时候会抛出NoNodeException
监听:
监听分为监听Node和Path,node有nodeUpdate和nodeDelete时间,PathChildrenCache有添加子节点,删除子节点等监听,此处不再细说
其余Election,Lock,Automic等有兴趣的话可以去百度,很多