1. 方法1
@Data
@Component
@ConfigurationProperties(prefix = “curator”)
1.1. 配置文件
application.properties
curator.retryCount=5 #重试次数
curator.elapsedTimeMs=5000 #重试间隔时间
curator.connectString=127.0.0.1:2181 # zookeeper 地址
curator.sessionTimeoutMs=60000 # session超时时间
curator.connectionTimeoutMs=5000 # 连接超时时间
1.2.配置类编写
package com.zxr.micro.config.zookeeper;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "curator")
public class WrapperZk {
private int retryCount;
private int elapsedTimeMs;
private String connectString;
private int sessionTimeoutMs;
private int connectionTimeoutMs;
}
1.3.@Autowired注入使用
package com.zxr.micro.config.zookeeper;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ZkConfiguration {
@Autowired
WrapperZk wrapperZk;
@Bean(initMethod = "start")
public CuratorFramework curatorFramework() {
return CuratorFrameworkFactory.newClient(
wrapperZk.getConnectString(),
wrapperZk.getSessionTimeoutMs(),
wrapperZk.getConnectionTimeoutMs(),
new RetryNTimes(wrapperZk.getRetryCount(), wrapperZk.getElapsedTimeMs()));
}
}
2. 方法二
@Value
import org.springframework.beans.factory.annotation.Value;
@Value("${curator.retryCount}")
private int retryCount;
@Value("${curator.connectString}")
private String connectString;