创建节点
static String path = "/test/task";
public static void main(String[] args) {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
CuratorFramework cf = CuratorFrameworkFactory.newClient("127.0.0.1:2181",
5000,1000,retryPolicy);
cf.start();
try {
CuratorUtils.createIfNotExists(cf,
path,
CreateMode.PERSISTENT,
StringUtils.toUtf8("hello"),
20);
}
catch (KeeperException.NodeExistsException e) {
log.info("Skipping create path[%s], since it already exists.", path);
}catch (Exception e){
log.info("error create path[%s]", path);
}
}
- CuratorUtils(来自druid.io 的源码)
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
public class CuratorUtils {
public static final int DEFAULT_MAX_ZNODE_BYTES = 512 * 1024;
private static final Logger log = new Logger(CuratorUtils.class);
/**
* Create znode if it does not already exist. If it does already exist, this does nothing. In particular, the
* existing znode may have a different payload or create mode.
*
* @param curatorFramework curator
* @param path path
* @param mode create mode
* @param rawBytes payload
* @param maxZnodeBytes maximum payload size
*
* @throws IllegalArgumentException if rawBytes.length > maxZnodeBytes
* @throws Exception if Curator throws an Exception
*/
public static void createIfNotExists(
CuratorFramework curatorFramework,
String path,
CreateMode mode,
byte[] rawBytes,
int maxZnodeBytes
) throws Exception
{
verifySize(path, rawBytes, maxZnodeBytes);
if (curatorFramework.checkExists().forPath(path) == null) {
try {
curatorFramework.create()
.creatingParentsIfNeeded()
.withMode(mode)
.forPath(path, rawBytes);
}
catch (KeeperException.NodeExistsException e) {
log.info("Skipping create path[%s], since it already exists.", path);
}
}
}
/**
* Create znode if it does not already exist. If it does already exist, update the payload (but not the create mode).
* If someone deletes the znode while we're trying to set it, just let it stay deleted.
*
* @param curatorFramework curator
* @param path path
* @param mode create mode
* @param rawBytes payload
* @param maxZnodeBytes maximum payload size
*
* @throws IllegalArgumentException if rawBytes.length > maxZnodeBytes
* @throws Exception if Curator throws an Exception
*/
public static void createOrSet(
CuratorFramework curatorFramework,
String path,
CreateMode mode,
byte[] rawBytes,
int maxZnodeBytes
) throws Exception
{
verifySize(path, rawBytes, maxZnodeBytes);
boolean created = false;
if (curatorFramework.checkExists().forPath(path) == null) {
try {
curatorFramework.create()
.creatingParentsIfNeeded()
.withMode(mode)
.forPath(path, rawBytes);
created = true;
}
catch (KeeperException.NodeExistsException e) {
log.debug("Path [%s] created while we were running, will setData instead.", path);
}
}
if (!created) {
try {
curatorFramework.setData()
.forPath(path, rawBytes);
}
catch (KeeperException.NoNodeException e) {
log.warn("Someone deleted path[%s] while we were trying to set it. Leaving it deleted.", path);
}
}
}
private static void verifySize(String path, byte[] rawBytes, int maxZnodeBytes)
{
if (rawBytes.length > maxZnodeBytes) {
throw new IAE(
"Length of raw bytes for znode[%s] too large[%,d > %,d]",
path,
rawBytes.length,
maxZnodeBytes
);
}
}
}
set / get 节点数据
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
CuratorFramework cf = CuratorFrameworkFactory.newClient("127.0.0.1:2181",
5000,1000,retryPolicy);
cf.start();
try {
byte[] newData = StringUtils.toUtf8("hello_world");
CuratorUtils.createOrSet(cf,
path,
CreateMode.PERSISTENT,
newData,
20);
final byte[] bytes = cf.getData().forPath(path);
String val = new String(bytes);
System.out.println("get data from zkNode:" + val);
}
catch (KeeperException.NodeExistsException e) {
log.info("Skipping create path[%s], since it already exists.", path);
}catch (Exception e){
log.info("error create path[%s]", path);
}
监听节点
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
CuratorFramework cf = CuratorFrameworkFactory.newClient("127.0.0.1:2181",
5000,1000,retryPolicy);
cf.start();
try {
Stat stat = cf.checkExists().usingWatcher(
(CuratorWatcher) watchedEvent -> {
switch (watchedEvent.getType()) {
case NodeDeleted:
break;
case NodeDataChanged:
System.out.println("NodeDataChanged:" + watchedEvent.getPath());
break;
default:
// do nothing
}
}
).forPath(path);
int dataLength = stat.getDataLength();
System.out.println("dataLength:" + dataLength);
}catch (Exception e){
log.info("error", path);
}
EPHEMERAL 节点
临时节点的生命周期和客户端会话绑定。如果客户端会话失效,那么这个节点就会自动被清除掉。注意,这里提到的是会话失效,而非连接断开;另外,在临时节点下面不能创建子节点
public static void main(String[] args) {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
CuratorFramework cf = CuratorFrameworkFactory.newClient("127.0.0.1:2181",
5000,1000,retryPolicy);
cf.start();
try {
byte[] newData = StringUtils.toUtf8("host1,host2");
CuratorUtils.createIfNotExists(cf,
path,
CreateMode.EPHEMERAL,
newData,
20);
final byte[] bytes = cf.getData().forPath(path);
String val = new String(bytes);
System.out.println("get data from zkNode:" + val);
}
catch (KeeperException.NodeExistsException e) {
log.info("Skipping create path[%s], since it already exists.", path);
}catch (Exception e){
log.info("error create path[%s]", path);
}
try {
TimeUnit.SECONDS.sleep(20);
}catch (Exception e){
}
cf.close();
}