import org.apache.zookeeper.*; public class ZooKeeperExample { private static final int SESSION_TIMEOUT = 3000; private ZooKeeper zooKeeper; public void connect(String hosts) throws IOException, InterruptedException { CountDownLatch connectedSignal = new CountDownLatch(1); zooKeeper = new ZooKeeper(hosts, SESSION_TIMEOUT, event -> { if (event.getState() == Watcher.Event.KeeperState.SyncConnected) { connectedSignal.countDown(); } }); connectedSignal.await(); } public void createNode(String path, byte[] data) throws KeeperException, InterruptedException { zooKeeper.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } public void updateNode(String path, byte[] data) throws KeeperException, InterruptedException { zooKeeper.setData(path, data, zooKeeper.exists(path, true).getVersion()); } public void deleteNode(String path) throws KeeperException, InterruptedException { zooKeeper.delete(path, zooKeeper.exists(path, true).getVersion()); } public byte[] getNodeData(String path) throws KeeperException, InterruptedException { return zooKeeper.getData(path, false, null); } public void closeConnection() throws InterruptedException { zooKeeper.close(); } public static void main(String[] args) { String hosts = "localhost:2181"; String path = "/example"; byte[] data = "Hello, ZooKeeper!".getBytes(); try { ZooKeeperExample example = new ZooKeeperExample(); example.connect(hosts); example.createNode(path, data); byte[] nodeData = example.getNodeData(path); System.out.println("Node data: " + new String(nodeData)); example.updateNode(path, "Hello, New ZooKeeper!".getBytes()); byte[] updatedNodeData = example.getNodeData(path); System.out.println("Updated node data: " + new String(updatedNodeData)); example.deleteNode(path); example.closeConnection(); e.printStackTrace(); } } }


上一篇:
下一篇:
切换中文