首先在application.properties添加配置
curator.retryCount=5
curator.elapsedTimeMs=5000
curator.connectString=127.0.0.1:2181
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 {
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);
}
}
|