分布式系统面临的配置问题:微服务意味着将单体应用拆分成一个个自服务,这些服务都是要相应的配置信息才能运行,随着系统内微服务数量越来越多,配置信息也不断地增多,所以一套集中式的、动态的配置管理设施是必不可少的。
概述
- SpringCloud Config是一个提供外部集中式配置管理的设施,配置服务器为各种不同的额微服务应用提供了一个中心化的外部配置
- SpringCloud Config分为客户端和服务端两部分
- 服务端:分布式配置中心,是一个独立的微服务,用来连接并为客户端提供配置信息,加密/解密信息等访问接口
- 客户端:通过指定的配置中心获取配置资源,cloud推荐用git来存储配置信息
- SpringCloud Config解决的问题:
- 集中管理配置文件
- 不同环境不同配置,动态化的配置更新
- 运行期间动态调整配置,不再需要在每个服务部署的机器上编写配置文件,让服务中心统一为服务拉取配置文件
- 当配置发生变动时,服务不需要重启即可感知配置变化并应用
- 将配置信息以REST接口形式暴露
SpringCloud Config服务端与Github通讯
目标:将配置文件部署在github,Config服务端从github获取配置
案例
- 新建ConfigServer模块并配置pom.xml
<!-- springCloud Config -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<!-- 避免Config的Git插件报错:org/eclipse/jgit/api/TransportConfigCallback -->
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
<version>4.10.0.201712302008-r</version>
</dependency>
- 建立远程仓库,并上传配置文件。如下例
spring:
profiles:
active:
- dev
---
spring:
profiles: dev
application:
name: microservicecloud-config-XXX-dev
---
spring:
profiles: test
application:
name: microservicecloud-config-XXX-test
- 在application.xml文件中配置github地址
server:
port: 3344
spring:
application:
#为这个服务取名,非常重要!!!!!
name: microservicecloud-config
cloud:
config:
server:
git:
# uri填github上仓库地址
uri: https://github.com/XXXX/SpringCloud_Configuration.git
- 编写主启动类,加入@EnableConfigServer注解
@SpringBootApplication
@EnableConfigServer
public class ConfigServer3344_APP {
public static void main(String[] args) {
SpringApplication.run(ConfigServer3344_APP.class,args);
}
}
- 启动服务并尝试访问配置文件,有以下五种访问配置规则
- {application}:配置文件的文件名
- {profile}:读取的环境
- {lable}:分支
/{application}/{profile}[/{lable}]
/{application}-{profile}.yml
/{lable}/{application}-{profile}.yml
/{application}-{profile}.properties
/{lable}/{application}-{profile}.properties
可用例子(返回格式可能不大相同,但返回值相同):
- http://config3344.com:3344/application-test.yml
- http://config3344.com:3344/master/application-dev.yml
- http://config3344.com:3344/application-test.yml/master
不可用例子:
- 没有该环境,返回空值:http://config3344.com:3344/application-test11.yml/master
- 没有配置文件,犯回错误页面:http://config3344.com:3344/lkjliiusdfsddsfl.yml