合理的配置中心所具备的功能如下:
提供服务端和客户端支持
集中管理各环境的配置文件
配置文件修改之后,可以快速的生效
可以进行版本管理
支持大的并发查询
支持各种语言
Spring Cloud Config可以完美的支持以上所有的需求。
Spring cloud使用git或svn存放配置文件,默认情况下使用git,以git为例做一套示例。
server 端
启动类添加@EnableConfigServer
,激活对配置中心的支持
请求地址:http://localhost:8001/neo-config/test
git 地址:https://github.com/shihongwei/springcloud-config-server
client 端
需要配置两个配置文件,application.properties和bootstrap.properties
application.properties如下:
spring.application.name=spring-cloud-config-client
server.port=8002
bootstrap.properties如下:
spring.cloud.config.name=neo-config
spring.cloud.config.profile=dev
spring.cloud.config.uri=http://localhost:8001/
spring.cloud.config.label=master
特别注意:上面这些与spring-cloud相关的属性必须配置在bootstrap.properties中,config部分内?>容才能被正确加载。因为config的相关配置会先于application.properties,而bootstrap.properties >的加载也是先于application.properties。
启动类只需要@SpringBootApplication
注解就可以
使用@Value
注解来获取server端参数的值
@RestController
class HelloController {
@Value("${config.hello}")
private String hello;
@RequestMapping("/hello")
public String getHello() {
return hello;
}
}
启动项目后访问:http://localhost:8002/hello
git 地址:https://github.com/shihongwei/springcloud-config-client
我们再进行一些小实验,手动修改neo-config-test.properties
中配置信息为:config.hello=hello in test update
提交到github,再次在浏览器访问http://localhost:8002/hello
,返回:hello in test
,说明获取的信息还是旧的参数,这是为什么呢?因为springboot项目只有在启动的时候才会获取配置文件的值,修改github信息后,client端并没有在次去获取,所以导致这个问题。如何去解决这个问题呢?留到下一章我们在介绍。
参考:纯洁的微笑
http://www.ityouknow.com/springcloud/2017/05/22/springcloud-config-git.html
转载于:https://www.jianshu.com/p/6d8a54f52d6c