|
| 1 | +package com.baeldung.zookeeper.manager; |
| 2 | + |
| 3 | +import org.apache.zookeeper.CreateMode; |
| 4 | +import org.apache.zookeeper.KeeperException; |
| 5 | +import org.apache.zookeeper.ZooDefs; |
| 6 | +import org.apache.zookeeper.ZooKeeper; |
| 7 | + |
| 8 | +import com.baeldung.zookeeper.connection.ZKConnection; |
| 9 | + |
| 10 | +public class ZKManagerImpl implements ZKManager { |
| 11 | + private static ZooKeeper zkeeper; |
| 12 | + private static ZKConnection zkConnection; |
| 13 | + |
| 14 | + public ZKManagerImpl() { |
| 15 | + initialize(); |
| 16 | + } |
| 17 | + |
| 18 | + /** * Initialize connection */ |
| 19 | + private void initialize() { |
| 20 | + try { |
| 21 | + zkConnection = new ZKConnection(); |
| 22 | + zkeeper = zkConnection.connect("localhost"); |
| 23 | + } catch (Exception e) { |
| 24 | + System.out.println(e.getMessage()); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + public void closeConnection() { |
| 29 | + try { |
| 30 | + zkConnection.close(); |
| 31 | + } catch (InterruptedException e) { |
| 32 | + System.out.println(e.getMessage()); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + public void create(String path, byte[] data) throws KeeperException, InterruptedException { |
| 37 | + zkeeper.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); |
| 38 | + } |
| 39 | + |
| 40 | + public Object getZNodeData(String path, boolean watchFlag) { |
| 41 | + try { |
| 42 | + byte[] b = null; |
| 43 | + b = zkeeper.getData(path, null, null); |
| 44 | + String data = new String(b, "UTF-8"); |
| 45 | + System.out.println(data); |
| 46 | + return data; |
| 47 | + } catch (Exception e) { |
| 48 | + System.out.println(e.getMessage()); |
| 49 | + } |
| 50 | + return null; |
| 51 | + } |
| 52 | + |
| 53 | + public void update(String path, byte[] data) throws KeeperException, InterruptedException { |
| 54 | + int version = zkeeper.exists(path, true) |
| 55 | + .getVersion(); |
| 56 | + zkeeper.setData(path, data, version); |
| 57 | + } |
| 58 | +} |
0 commit comments