本章将介绍如何从Apollo配置中心获取配置。
专栏目录:
欢迎关注个人公众号: Coder编程
欢迎关注个人网站:www.52melrin.com
一、Maven 依赖
如果项目是Maven项目的话,这里需要将Apollo源码从github下载下来。然后package至本地,或者上传至公司的三方仓库。才可以引入以下依赖。
<dependency> <groupId>com.ctrip.framework.apollo</groupId> <artifactId>apollo-client</artifactId> <version>0.10.2</version> </dependency>
二、Java客户端用法
Apollo提供了API方式和Spring整合方式。
我们该如何选择呢?
- API方式灵活,功能完备,配置值实时更新(热发布),支持所有Java环境。
- Spring方式接入简单,结合Spring有N种酷炫的玩法,如
- Placeholder方式:
- 代码中使用,如:
@Value("${someKeyFromApollo:someDefaultValue}")
- application.properties中使用,如:
spring.datasource.url: ${someKeyFromApollo:someDefaultValue}
- 代码中使用,如:
- Spring boot的@ConfigurationProperties方式
- 从v0.10.0开始的版本支持placeholder在运行时自动更新,具体参见PR #972。(v0.10.0之前的版本在配置变化后不会重新注入,需要重启才会更新,如果需要配置值实时更新,可以参考后续3.2.2 Spring Placeholder的使用的说明)
- Placeholder方式:
- Spring方式也可以结合API方式使用,如注入Apollo的Config对象,就可以照常通过API方式获取配置了:
@ApolloConfig private Config config; //inject config for namespace application
下面我们简单介绍下API的使用,和Spring的整合。
2.1 通过Placeholder方式获取
TestController
@RestController public class TestController { @Value("${timeout:200}") private Integer timeout; @RequestMapping("/test") public String test(){ return "获取超时时间: "+timeout; } }
测试结果:
2.2 通过@ConfigurationProperties方式获取
application.properties
timeout:${timeout}
TestProperties.java
@ConfigurationProperties @Component public class TestProperties { private Integer timeout; public Integer getTimeout() { return timeout; } public void setTimeout(Integer timeout) { this.timeout = timeout; } }
TestController2.java
@RestController public class TestController2 { @Autowired private TestProperties testProperties; @RequestMapping("/test2") public String test() { return "获取超时时间:"+testProperties.getTimeout(); } }
测试结果:
2.3 通过Spring 结合 API 方式
TestController3
@RestController public class TestController3 { @ApolloConfig private Config config; @RequestMapping("/test3") public String test() { return "获取超时时间:"+config.getIntProperty("timeout", 200); } }
测试结果:
2.4 API 方式
API方式灵活,功能完备,配置值实时更新(热发布),支持所有Java环境。
TestController4.java
@RestController public class TestController4 { private Config config = ConfigService.getAppConfig(); @RequestMapping("/test4") public String test() { return "获取超时时间:"+config.getIntProperty("timeout", 200); } }测试结果: