增删改查节点
package com.org.zookeeper.crud;
import com.org.zookeeper.ClientFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import java.util.List;
@Slf4j
public class NodeOperation {
public static final String ZK_ADDRESS = "127.0.0.1:2181";
public static final String ZK_PATH = "/test/CURD/node-1";
public static final String PARENT_PATH = "/test";
public void createNode() {
CuratorFramework client = ClientFactory.createSimple(ZK_ADDRESS);
try {
client.start();
String data = "hello";
byte[] payload = data.getBytes("UTF-8");
client.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.PERSISTENT)
.forPath(ZK_PATH, payload);
} catch (Exception e) {
e.printStackTrace();
} finally {
client.close();
}
}
public void readNode() {
CuratorFramework client = ClientFactory.createSimple(ZK_ADDRESS);
try {
client.start();
Stat stat = client.checkExists().forPath(ZK_PATH);
if (stat != null) {
byte[] payload = client.getData().forPath(ZK_PATH);
String data = new String(payload, "UTF-8");
log.info("read data:" + data);
List<String> children = client.getChildren().forPath(PARENT_PATH);
children.forEach(child -> log.info("child: " + children));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
client.close();
}
}
public void updateNode() {
CuratorFramework client = ClientFactory.createSimple(ZK_ADDRESS);
try {
client.start();
String data = "hello world";
byte[] payload = data.getBytes("UTF-8");
client.setData().forPath(ZK_PATH, payload);
} catch (Exception e) {
e.printStackTrace();
} finally {
client.close();
}
}
public void updatNodeAsync() {
CuratorFramework client = ClientFactory.createSimple(ZK_ADDRESS);
try {
AsyncCallback.StringCallback callback = new AsyncCallback.StringCallback() {
@Override
public void processResult(int i, String s, Object o, String s1) {
log.info(
"i = " + i + " | " +
"s = " + s + " | " +
"o = " + o + " | " +
"s1 = " + s1
);
}
};
client.start();
String data = "hello world!";
byte[] payload = data.getBytes("UTF-8");
client.setData()
.inBackground(callback)
.forPath(ZK_PATH, payload);
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
} finally {
client.start();
}
}
public void deleteNode() {
CuratorFramework client = ClientFactory.createSimple(ZK_ADDRESS);
try {
client.start();
client.delete().forPath(ZK_ADDRESS);
List<String> children = client.getChildren().forPath(PARENT_PATH);
for (String child : children) {
log.info("child: " + child);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
client.close();
}
}
}
分布式ID生成器
package com.org.zookeeper.distributeIdgenerator;
import com.org.zookeeper.ClientFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
@Slf4j
public class IDMaker {
public static final String ZK_ADDRESS = "";
CuratorFramework client = ClientFactory.createSimple(ZK_ADDRESS);
private String createSeqNode(String pathPerfix) {
try {
client.start();
String destPath = client.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
.forPath(pathPerfix);
return destPath;
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
client.close();
}
return null;
}
public String makeId(String nodeName) {
String str = createSeqNode(nodeName);
if (null == str) {
return null;
}
int index = str.lastIndexOf(nodeName);
if (index > 0) {
index += str.length();
return index <= str.length() ? str.substring(index) : "";
}
return str;
}
}
分布式锁
package com.org.zookeeper.distributelock;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
@Getter
@Setter
@Slf4j
public class ZkLock implements AsyncCallback.StringCallback, AsyncCallback.Children2Callback, Watcher {
ZooKeeper zk;
CountDownLatch cd = new CountDownLatch(1);
String ZK_PATH = "/lock";
String lockName;
String threadName;
public void tryLock() {
try {
zk.create(ZK_PATH, threadName.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL,
this, threadName);
cd.await();
} catch (Exception e) {
e.printStackTrace();
}
}
public void unlock() {
try {
zk.delete("/" + lockName, -1);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
}
}
@Override
public void processResult(int i, String path, Object ctx, String name) {
log.info(ctx.toString() + " create path: " + name);
lockName = name.substring(1);
zk.getChildren("/", false, this, ctx);
}
@Override
public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
if (children == null) {
log.error(ctx.toString() + "children null");
} else {
try {
Collections.sort(children);
int i = children.indexOf(lockName);
if (i < 1) {
log.info(threadName + " is first...");
zk.setData("/", threadName.getBytes(), -1);
cd.countDown();
} else {
log.info(threadName + " watch " + children.get(i -1));
zk.exists("/" + children.get(i - 1), this);
}
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void process(WatchedEvent watchedEvent) {
Event.EventType type = watchedEvent.getType();
switch (type) {
case NodeDeleted:
zk.getChildren("/", false, this, "");
case NodeChildrenChanged:
break;
}
}
}