SpringBoot读取配置文件

SpringBoot读取配置文件,第1张

首先在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.bootgroupId>
    <artifactId>spring-boot-configuration-processorartifactId>
    <optional>trueoptional>
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);
		}
	}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/919111.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存