创建了一个SpringBoot项目,引入pom依赖
org.apache.curator
curator-framework
4.2.0
org.apache.curator
curator-client
4.2.0
org.apache.curator
curator-recipes
4.2.0
org.apache.zookeeper
zookeeper
3.4.6
org.slf4j
slf4j-log4j12
log4j
log4j
配置application.yml属性
curator: #重试次数 maxRetries: 3 #重试间隔时间 baseSleepTimeMs: 1000 # zookeeper 地址 多个可用逗号分隔127.0.0.1:2181,127.0.0.1:2182 connectString: 192.168.106.128:2181 # session超时时间 sessionTimeoutMs: 60000 # 连接超时时间 connectionTimeoutMs: 5000 path: /distributed-lock
配置注入Bean
package com.example.zkConfig;
import lombok.Data;
import org.apache.curator.framework.Curatorframework;
import org.apache.curator.framework.CuratorframeworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
public class ZookeeperConfig {
@Value("${curator.maxRetries}")
private int maxRetries;
@Value("${curator.baseSleepTimeMs}")
private int baseSleepTimeMs;
@Value("${curator.connectString}")
private String connectString;
@Value("${curator.sessionTimeoutMs}")
private int sessionTimeoutMs;
@Value("${curator.connectionTimeoutMs}")
private int connectionTimeoutMs;
@Value("${curator.path}")
private String path;
//调用start初始化方法
@Bean(initMethod = "start")
public Curatorframework curatorframework(){
return CuratorframeworkFactory.newClient(
this.connectString,
this.sessionTimeoutMs,
this.connectionTimeoutMs,
new RetryNTimes(this.maxRetries,this.connectionTimeoutMs)
);
}
}
测试文件ZkTest一些基本操作
package com.example;
import org.apache.curator.framework.Curatorframework;
import org.apache.zookeeper.CreateMode;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class ZkTest {
@Autowired
private Curatorframework curatorframework;
@Test
public void test1() throws Exception {
//创建持久节点
// String s = curatorframework.create().forPath("/test-node1");
// 创建临时序号节点
String s = curatorframework.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/test-node2", "abc".getBytes());
System.out.println(s);
}
@Test
public void test2() throws Exception {
//获取节点的数据
byte[] bytes = curatorframework.getData().forPath("/test-node1");
System.out.println(new String(bytes));
}
@Test
public void test3() throws Exception {
//修改节点的数据
curatorframework.setData().forPath("/test-node1","你好".getBytes());
//获取节点的数据
byte[] bytes = curatorframework.getData().forPath("/test-node1");
System.out.println(new String(bytes));
}
@Test
public void test4() throws Exception {
//创建若父节点不存在则先创建父节点
String s = curatorframework.create().creatingParentsIfNeeded().forPath("/node-parent/node-1");
System.out.println(s);
}
@Test
public void test5() throws Exception {
//删除父节点 子节点存在也一并删除
curatorframework.delete().guaranteed().deletingChildrenIfNeeded().forPath("/node-parent");
}
}



