随着微服务,分布式集群等技术流行。配置文件越来越多,越来越难管理。springcloud的配置中心,就是解决此问题的解决方案之一
Spring Cloud Config
在我们了解spring cloud config之前,我可以想想一个配置中心提供的核心功能应该有什么
- 提供服务端和客户端支持
- 集中管理各环境的配置文件
- 配置文件修改之后,可以快速的生效
- 可以进行版本管理
- 支持大的并发查询
- 支持各种语言
Spring Cloud Config可以完美的支持以上所有的需求。
Spring Cloud Config项目是一个解决分布式系统的配置管理方案。它包含了Client和Server两个部分,server提供配置文件的存储、以接口的形式将配置文件的内容提供出去,client通过接口获取数据、并依据此数据初始化自己的应用。
方式一、配置文件存在server服务上(native)
server端项目
1、添加依赖
<!-- 配置中心:服务端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
2、application.properties
server.port=8001
spring.application.name=config-server
# native 方式存储配置文件
spring.profiles.active=native
spring.cloud.config.server.native.search-locations=classpath:/config
3、启动类添加@EnableConfigServer
4、src/main/resource下config文件夹,创建config-server-dev.properites文件。文件内容如下
neo.hello=hello everybody sdsdsds
forbid.ip=127.0.0.1
client端项目
1、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 配置中心:客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
2、属性文件配置
a、application.properties
spring.application.name=spring-cloud-consumer
server.port=9001
b、bootstrap.properties
spring.cloud.config.name=config-server
spring.cloud.config.profile=dev
spring.cloud.config.uri=http://localhost:8001/
3、controller配置
@Value("${neo.hello}")
private String hello;
@Value("${forbid.ip}")
private String forbidIp;
@RequestMapping("/hello")
public String from() {
return this.hello+"===="+this.forbidIp;
}
测试
方式二、配置文件存在git上
server端项目
1、在github上创建文件夹prop,文件夹下创建config-server-dev.properties
neo.hello=hello everybody sdsdsds
forbid.ip=127.0.0.1
2、配置application.properties
server.port=8001
spring.application.name=config-server
spring.profiles.active=git
spring.cloud.config.server.git.uri=https://github.com/xxx/xxx.git
spring.cloud.config.server.git.search-paths=prop
spring.cloud.config.server.git.username=
spring.cloud.config.server.git.password=
注意:方式一和方式二的只有服务端的application.properties配置有区别,其他所有都参照方式一配置
测试
注意测试url是:http://localhost:8001/config-server/dev