zookeeper增删改查节点操作
java 与zk 增删改查的演示例
pom.xml
1 2 3 4 5 | <dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-framework</artifactId> <version> 4.0 . 0 </version> </dependency> |
这个是基于curator客户端对zookeeper的增删改查操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | /** * zookeeper 节点的新增,修改,删除 * Date:2019/8/17 * Author:gyc * Desc: */ public class ZookeeperHello { public static final String CONNECT_STR = "192.168.3.14:2181" ; public CuratorFramework curatorFramework = null ; @Before public void before() { CuratorFramework tmpCuratorFramework = CuratorFrameworkFactory.builder() .connectString(CONNECT_STR).sessionTimeoutMs( 1000 ).retryPolicy( new ExponentialBackoffRetry( 1000 , 1 )) .namespace( "curator" ) .build(); tmpCuratorFramework.start(); this .curatorFramework = tmpCuratorFramework; tmpCuratorFramework.start(); this .curatorFramework = tmpCuratorFramework; } /** * 创建一个永久的节点 * @throws Exception */ @Test public void createNode() throws Exception { curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT) .forPath( "/newNode" , "text" .getBytes()); } /** * 修改一个节点 */ @Test public void udpateNode() throws Exception { curatorFramework.setData().forPath( "/newNode" , "value" .getBytes()); } /** * 获取一个节点信息 */ @Test public void getNodeData() throws Exception { byte [] bytes = curatorFramework.getData().forPath( "/newNode" ); String value = new String(bytes); System.out.println(value); } /** * 删除节点 * @throws Exception */ @Test public void deleteNode() throws Exception { curatorFramework.delete().forPath( "/newNode" ); } /** * 测试一个节点是否存在 * @throws Exception */ @Test public void checkNodeExist() throws Exception { Stat stat = curatorFramework.checkExists().forPath( "/newNode" ); //stat 返回空代表不存在 System.out.println(stat); } /** * 创建一个临时节点 */ @Test public void createTempNode() throws Exception { curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath( "/tmpNode" , "tmpNode" .getBytes()); } } |
解析一下:
CuratorFramework tmpCuratorFramework = CuratorFrameworkFactory.builder()
.connectString(CONNECT_STR).sessionTimeoutMs(1000).retryPolicy(new ExponentialBackoffRetry(1000, 1))
.namespace("curator")
.build();
重试策略:Curator 内部实现的几种重试策略:
• ExponentialBackoffRetry:重试指定的次数, 且每一次重试之
间停顿的时间逐渐增加.
• RetryNTimes:指定最大重试次数的重试策略
• RetryOneTime:仅重试一次
• RetryUntilElapsed:一直重试直到达到规定的时间
namespace: 值得注意的是 session2 会话含有隔离命名空间,即
客户端对 Zookeeper 上数据节点的任何操作都是相对/curator
目录进行的,这有利于实现不同的 Zookeeper 的业务之间的隔
离
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步