PageRenderTime 286ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/important-library/src/main/java/com/github/curator_zookeeper/CuratorPractice1.java

https://gitlab.com/doctorwho1986/doctor
Java | 156 lines | 120 code | 36 blank | 0 comment | 9 complexity | f642735d3b41efdd3658dafb8ae52b10 MD5 | raw file
  1. package com.github.curator_zookeeper;
  2. import java.nio.charset.StandardCharsets;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. import java.util.concurrent.Executors;
  6. import org.apache.curator.framework.CuratorFramework;
  7. import org.apache.curator.framework.CuratorFrameworkFactory;
  8. import org.apache.curator.framework.api.CuratorWatcher;
  9. import org.apache.curator.framework.recipes.cache.ChildData;
  10. import org.apache.curator.framework.recipes.cache.NodeCache;
  11. import org.apache.curator.framework.recipes.cache.NodeCacheListener;
  12. import org.apache.curator.framework.recipes.cache.PathChildrenCache;
  13. import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
  14. import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
  15. import org.apache.curator.retry.RetryNTimes;
  16. import org.apache.zookeeper.CreateMode;
  17. import org.apache.zookeeper.WatchedEvent;
  18. import org.apache.zookeeper.Watcher.Event.EventType;
  19. import org.apache.zookeeper.ZooDefs;
  20. import org.apache.zookeeper.data.Stat;
  21. import org.slf4j.Logger;
  22. import org.slf4j.LoggerFactory;
  23. import com.alibaba.fastjson.JSON;
  24. public class CuratorPractice1 {
  25. private static final Logger LOG = LoggerFactory.getLogger(CuratorPractice1.class);
  26. private static CuratorFramework zk;
  27. private final static String namespace = "zk";
  28. private final static String path = "zk/curator";
  29. public static void main(String[] args) throws Exception {
  30. zk = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181")
  31. .namespace(namespace)
  32. .retryPolicy(new RetryNTimes(5, 1000))
  33. .connectionTimeoutMs(30000)
  34. .build();
  35. zk.start();
  36. watchNodeData(zk, path);
  37. WatchPathCache(zk, namespace);
  38. Stat forPath = zk.checkExists().forPath(path);
  39. if (forPath != null) {
  40. zk.delete().deletingChildrenIfNeeded().forPath(path);
  41. LOG.info("{msg:'{} is exist and delete'}", path);
  42. } else {
  43. LOG.warn("{msg:'{} is exist'}", path);
  44. }
  45. zk.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT)
  46. .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
  47. .forPath(path);
  48. zk.setData().forPath(path, "doctorwho".getBytes(StandardCharsets.UTF_8));
  49. byte[] data = zk.getData().usingWatcher(new ZkWatch(path)).forPath(path);
  50. data = zk.getData().forPath(path);
  51. System.out.println("get:" + new String(data, StandardCharsets.UTF_8));
  52. while (true) {
  53. }
  54. }
  55. private static void watchNodeData(CuratorFramework zk, String path) throws Exception {
  56. final NodeCache nodeCache = new NodeCache(zk, path);
  57. nodeCache.getListenable().addListener(new NodeCacheListener() {
  58. @Override
  59. public void nodeChanged() throws Exception {
  60. final ChildData currentData = nodeCache.getCurrentData();
  61. Map<String, String> info = new HashMap<>();
  62. if (currentData != null) {
  63. info.put("path", currentData.getPath().toString());
  64. info.put("data", new String(currentData.getData(), StandardCharsets.UTF_8));
  65. info.put("stat", JSON.toJSONString(currentData.getStat()));
  66. }
  67. LOG.info("{msg:'nodeChanged info : {}'}", JSON.toJSONString(info));
  68. }
  69. }, Executors.newFixedThreadPool(2));
  70. nodeCache.start();
  71. }
  72. private static void WatchPathCache(CuratorFramework zk, String path) throws Exception {
  73. PathChildrenCache pathChildrenCache = new PathChildrenCache(zk, path, true);
  74. pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
  75. @Override
  76. public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
  77. Map<String, String> info = new HashMap<>();
  78. ChildData currentData = event.getData();
  79. info.put("path", currentData.getPath().toString());
  80. info.put("data", new String(currentData.getData(), StandardCharsets.UTF_8));
  81. info.put("stat", JSON.toJSONString(currentData.getStat()));
  82. String message = "watch path child event :";
  83. switch (event.getType()) {
  84. case CHILD_ADDED:
  85. message = message + " child add event";
  86. break;
  87. case CHILD_REMOVED:
  88. message = message + " child remove event";
  89. break;
  90. case CHILD_UPDATED:
  91. message = message + " child update event";
  92. break;
  93. case CONNECTION_LOST:
  94. case CONNECTION_RECONNECTED:
  95. case CONNECTION_SUSPENDED:
  96. case INITIALIZED:
  97. default:
  98. message = message + " unknown event";
  99. break;
  100. }
  101. LOG.info("{msg:{} :{}}", message, JSON.toJSONString(info));
  102. }
  103. });
  104. pathChildrenCache.start();
  105. }
  106. static class ZkWatch implements CuratorWatcher {
  107. private String path;
  108. ZkWatch(String path) {
  109. this.path = path;
  110. }
  111. @Override
  112. public void process(WatchedEvent event) throws Exception {
  113. LOG.info("{msg---:{}}", event);
  114. if (event.getType() == EventType.NodeDataChanged) {
  115. byte[] data = zk.getData().forPath(this.path);
  116. LOG.info("{msg:'get data {}'}", new String(data, StandardCharsets.UTF_8));
  117. }
  118. }
  119. }
  120. }