九阴真经


curator操作ZooKeeper

<p><strong>Curator操作ZooKeeper</strong></p> <h6>引包:</h6> <pre><code> &lt;!-- 对zookeeper的底层api的一些封装 --&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.curator&lt;/groupId&gt; &lt;artifactId&gt;curator-framework&lt;/artifactId&gt; &lt;version&gt;2.12.0&lt;/version&gt; &lt;/dependency&gt; &lt;!-- 封装了一些高级特性,如:Cache事件监听、选举、分布式锁、分布式Barrier --&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.curator&lt;/groupId&gt; &lt;artifactId&gt;curator-recipes&lt;/artifactId&gt; &lt;version&gt;2.12.0&lt;/version&gt; &lt;/dependency&gt;</code></pre> <h6>main函数操作</h6> <pre><code> RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", 5000, 5000, retryPolicy); client.start(); //创建节点 client.create().creatingParentContainersIfNeeded().withMode(CreateMode.EPHEMERAL) .forPath("/abc", "abc".getBytes()); client.create().creatingParentContainersIfNeeded().withMode(CreateMode.EPHEMERAL) .forPath("/a", "a".getBytes()); //获取节点 byte[] data = client.getData().forPath("/abc"); System.out.println(new String(data)); //更新节点数据 client.setData().forPath("/abc", "abcd".getBytes()); data = client.getData().forPath("/abc"); byte[] data_a = client.getData().forPath("/abc"); System.out.println(new String(data)); System.out.println(new String(data_a)); client.delete().forPath("/a"); System.out.println("删除a之后"); data_a = client.getData().forPath("/a"); System.out.println(new String(data_a));</code></pre> <h6>注入Bean</h6> <pre><code>package com.example.demo.config; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Zookeeper * * @author jxd * @version 1.0 * * @date 2020/12/9 14:47 */ @Configuration public class ZookeeperConfig { @Bean public CuratorFramework curatorFramework() { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", 5000, 5000, retryPolicy); client.start(); return client; } } </code></pre> <h6>使用:</h6> <pre><code> @Autowired private CuratorFramework curatorFramework; @GetMapping("/abcd") public Object testZ() throws Exception { curatorFramework.create().creatingParentContainersIfNeeded().withMode(CreateMode.EPHEMERAL) .forPath("/abc", "abc".getBytes()); byte[] data = curatorFramework.getData().forPath("/abc"); System.out.println(new String(data)); curatorFramework.delete().forPath("/abc"); return "1"; }</code></pre>

页面列表

ITEM_HTML