spring cloud config
微服务中,对于单个服务,都有单独的配置文件,properties/yum等,实现配置和代码的分离。而分布式配置中心是将配置文件放置在远程git/svn仓库中,在spring cloud中,使用spring cloud config实现分布式配置中心,以git为例,使用spring cloud config 建立config server,config server(服务端)保持与git之间的连接,将配置文件project-{profile}.properties存放在git仓库中,而单个微服务应用(config client客户端)再从config server中获取配置信息。
![](https://i-blog.csdnimg.cn/blog_migrate/2f305a440266644b633078e23e024444.png)
1、客户端应用启动,根据bootstrap.properties获取配置应用名{application},环境名{profille},分支名{lable},向configserver 获取配置
2、config server根据配置的git信息,和客户端的请求信息从git远端获取配置信息
3、config server 使用git clone 将配置信息clone到本地文件系统,起到缓存的作用。
4、config server 文件系统将配置信息返回到客户端
5、客户端 根据外部配置信息(config server获取到的)创建applicationcontext实例,该配置信息优先于jar包中的配置信息 ,整个过程over.....
代码实践
构建config server 服务端
1、 服务端引入maven
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
<version>1.5.4.RELEASE</version>
</dependency>
2、创建配置文件 bootstrap-dev.properties 、bootstrap-test.properties
test = dev
test = test
推送到远端git仓库中, https://192.169.22.134/configServerTest
3、配置config server的properties
server.port=8081
#服务的git仓库地址
spring.cloud.config.server.git.uri=https://192.169.22.134/configServerTest
#配置文件所在的目录
spring.cloud.config.server.git.search-paths=/**
#配置文件所在的分支
spring.cloud.config.label=master
#git仓库的用户名
spring.cloud.config.username=lilelife
#git仓库的密码
spring.cloud.config.password=********
4、启动类@EnableConfigServer修饰主类
@SpringBootApplication
@EnableConfigServer
@EnableEurekaClient
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
然后运行main方法启动config server,
访问localhost:8081/bootstrap-dev.properties 或-test.properties可以获取到两个git仓库中 的配置文件(dev test)中的信息。获取配置信息的url 可以参考
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
至此服务端config server 完成。
构建客户端
1、maven 同服务端
2、.properties 配置文件
#配置文件所在分支
spring.cloud.config.label=master
spring.cloud.config.profile=prod
#配置服务中心
spring.cloud.config.uri=http://localhost:8081/
3、获取配置信息 上面两个git仓库文件中的 test = dev ; test = test
@RefreshScope// 实现配置文件自动刷新
public class A{
@value("${test}")
private String test ;
}