首先在application.properties添加配置
# 重试次数
curator.retryCount=5
# 重试间隔
curator.elapsedTimeMs=5000
# zookeeper地址
curator.connectString=127.0.0.1:2181
# session超时时间
curator.sessionTimeoutMs=60000
# 连接超时时间
curator.connectionTimeoutMs=5000
创建WrapperZK来读取配置文件
@Data
@Component
@ConfigurationProperties(prefix = "curator")
public class WrapperZK {
private int retryCount;
private int elapsedTimeMs;
private String connectString;
private int sessionTimeoutMs;
private int connectionTimeoutMs;
}
注意 curator,就是配置文件的前缀,然后会发现idea会提示未配置Srping Boot 配置注解处理器
解决办法:在pom文件中添加下面的依赖即可
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
使用
@Configuration
public class CuratorConfig {
@Autowired
private WrapperZK wrapperZK;
@Bean
public CuratorFramework curatorFramework(){
return CuratorFrameworkFactory.newClient(wrapperZK.getConnectString(),
wrapperZK.getSessionTimeoutMs(),
wrapperZK.getConnectionTimeoutMs(),
new RetryNTimes(wrapperZK.getRetryCount(), wrapperZK.getElapsedTimeMs()));
}
}
测试
@Autowired
private CuratorFramework curatorFramework;
/**
* 创建节点
*/
@Test
public void createNode(){
try {
//start()开始连接,没有此会报错
//java.lang.IllegalStateException: Expected state [STARTED] was [LATENT]
curatorFramework.start();
// 阻塞直到连接成功
curatorFramework.blockUntilConnected();
//添加持久节点
String path = curatorFramework.create(). forPath("/node1");
// 添加临时序号节点
String path2 = curatorFramework.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/node2", "node2".getBytes());
System.out.println(String.format("path:%s,path2:%s,successful",path,path2));
//让系统在这里阻塞不退出
System.in.read();
} catch (Exception e) {
throw new RuntimeException(e);
}
}