【Spring Could】spring cloud config 统一配置中心
spring cloud config 统一配置中心
由于大型项目中可能存在大量的微服务,而每个微服务都有自己的配置文件(application.properties),导致存在以下问题:
1、大量的配置文件分散在各个微服务的代码中,不易管理
2、使用共同的配置时(例如数据库、redis),当共同的配置修改时,所有使用到的微服务的配置都需要修改
3、配置内容的安全性以及权限无法保障
4、配置更新后,相应的微服务需要重启
在spring cloud中使用config组件来统一管理配置文件,来解决以上存在的问题。
spring cloud config的原理类似于eureka,有server端和client端。server端负责从远端或本地的配置地址获取到配置文件,而各个微服务(client端)则从server端获取相应的配置。
config组件的原理图如下:
远端的配置存储地址 例如: github、svn等
本地存储地址 例如:本地文件夹
product、order等各个微服务从config server上获取相应的配置
config server也是一个微服务
Config Server 配置服务器
首先添加依赖 (这里配置以远端存储svn为例,所以也要添加svn依赖)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.tmatesoft.svnkit</groupId>
<artifactId>svnkit</artifactId>
<version>1.8.10</version>
</dependency>
在spring boot启动类上添加@EnableConfigServer注解,表示这是一个Config Server
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
配置文件中配置端口号、应用名、远端svn的url(认证账号、密码)
server:
port: 8888
spring:
application:
name: config-server
cloud:
config:
server:
svn:
uri: https://127.0.0.1/svn/springCloudConfig/
username: xcx
password: 445259804
default-label: springCloudConfig
profiles:
active: subversion
这里的default-label可以理解为 取https://127.0.0.1/svn/springCloudConfig/springCloudConfig路径下的配置,若配置为空则取
https://127.0.0.1/svn/springCloudConfig/路径下的配置,若不配,svn默认为取trunk(https://127.0.0.1/svn/springCloudConfig/trunk)路径下的配置。
我的远端svn也设置的是本机
各个文件的内容:
请求结果如下:
当请求路径在对应的远端路径下找不到相应的文件配置,则会取application.yml或application.properties文件下的配置。
Config Client 配置客户端
配置客户端,也需要添加相应的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
这次不用在spring boot的启动类上添加注解了!
由于spring cloud是先由bootstrap.yml文件去config server上读取配置文件,默认的没有bootstrap.yml或bootstrap.yml文件内容为空,则以http://localhost:8888为配置中心的url。若本地配置的Config Server端口号不为8888,则会导致取不到远程的配置内容。
(其实也是可以理解的,本来就是要去取远程的配置文件,那么配置远程Config Server肯定是不应该写在application.yml文件中的。bootstrap.yml中的配置内容是比application.yml先加载的)
所以配置 远程配置服务器的内容应该写在bootstrap.yml文件中
bootstrap.yml内容如下:
spring:
cloud:
config:
uri: http://localhost:8888
profile: dev
# label: springCloudConfig
application:
name: config-client
application.yml中配置端口号:
server:
port: 8889
测试Controller内容如下:
@RestController
public class PropertiesController {
@Value("${profile}")
private String profile;
@GetMapping("/getProperties")
public String getUser() {
return profile;
}
}
访问http://localhost:8889/getProperties,结果如下:
这里会根据 应用名( spring.application.name=config-client)-profile(spring.cloud.config.profile=dev)去取文件,
即取到了http://localhost:8888/config-client-dev.properties的配置文件。