配置中心 Config
测试用项目环境
框架 | 版本 |
---|---|
Idea | 2019.2 |
JDK | 1.8 |
SpringBoot | 2.1.6.RELEASE |
SpringCloud | Greenwich.SR2 |
配置中心
顾名思义,可以将微服务系统中公用的配置提取出来统一管理,一次修改,面面俱到
相关产品
当前生态下配置中心有很多产品,公司内还会有自己开发的配置中心
- 百度:官方地址(disconf) github(knightliao/disconf)
- 阿里:github(takeseem/diamond)
- SpringCloud:官方文档(spring-cloud-config)
Config Server 配置中心搭建
创建一个新的SpringBoot引用
maven依赖
使用maven依赖管理,使用最新的springcloud Greenwich.SR2版本
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
配置中心同样需要注册到注册中心去所以需要eureka依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
config-server配置中心关依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<!--此处并不是starter-->
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
启动类注解
@EnableConfigServer
git管控中心
个人感觉Config Server相当于一个中转站,所以实际配置文件存放的地方是各种关系非关系形数据库,或git服务器。我此处采用了github私有仓库作为配置文件的存放地。
github上建好仓库生成一个url
application.yml配置
spring:
cloud:
config:
server:
git:
username: your github username
password: your github password
uri: your repository uri exp https://github.com/lmwis/course-except.git
# 超时时间
timeout: 4
# 默认分支
default-label: master
配置好之后启动
演示github内容:
浏览器访问:
http://localhost:9090/master/test-master.yml
你就会得到:
后缀修改为json,config server还会帮你吧yml转化为json
命名规则
/{name}-{profiles}.properties
/{name}-{profiles}.yml
/{name}-{profiles}.json
/{label}/{name}-{profiles}.yml
name 文件名称
profile 环境名称,开发、测试、生产
lable 仓库分支、默认master分支
客户端使用配置中心
maven依赖
<!--配置中心-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>
yml配置
第一步
先将配置文件名application.yml替换为bootstrap.yml
从此application改名为bootstrap
我也很难接受
spring:
application:
name: test-service
cloud:
config:
discovery:
# 启用,必须为true
enabled: true
# 配置中心在注册中心的服务名 会自动负载均衡
service-id: FEHEAD-CONFIG-SERVER
# 指定当前分支
# 现在访问到的 /master/test-service-master.yml
# git上的文件名是test-service
profile: master
然后就可以像正常情况一样使用配置文件了
特别注意
如果你的git上有一个名为application.yml的配置文件
那么你当前git分支下的所有配置文件都会默认把application.yml加在一起,但application.yml的优先级比较低,同名字会被项目的配置文件覆盖