SpringCloudConfig
为微服务提供集中化的外部配置支持,为各个不同的微服务应用配置提供了一种集中化的配置。
注意点:存储在仓库的 yml 文件一定要是 UTF-8 的格式
用来访问 仓库 的项目
添加的依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
YML 配置
server:
port: 3345
spring:
application:
name: microservicecloud-config
cloud:
config:
server:
git:
uri: https://github.com/ChengCuo00/microservicecloud-config.git
# GitHub 上面的 git 仓库
在主启动类上面开启 config 添加注解:
@EnableConfigServer
此时已经可以通过这个类去获取 仓库 中配置信息了
官网给出的读取配置信息的 url 格式
/{application}/{profile}[/{label}]
http://config-3345.com:3345/application/dev/master
http://config-3345.com:3345/application/tes/master
http://config-3345.com:3345/application/xxx/master (不存在)
/{application}-{profile}.yml
http://config-3345.com:3345/application-dev.yml
http://config-3345.com:3345/application-test.yml
http://config-3345.com:3345/application-xxx.yml (不存在)
/{label}/{application}-{profile}.yml
http://config-3345.com:3345/master/application-dev.yml
http://config-3345.com:3345/master/application-test.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
第一种和第三种可以指定读取某个分支的配置信息
编写存储在 仓库 里面的配置文件 application.yml
spring:
profiles:
active:
- dev
---
spring:
profiles: dev
application:
name: microservicecloud-config-nianzuochen-dev
---
spring
profiles: test
application:
name: microservicecloud-config-nianzuochen-test
其中第一个文件中的信息是在查询的开发环境不存在的时候返回的信息
# 仅仅 返回 profile 内容
spring:
profiles:
active:
- dev
其他的项目
其他项目都是通过上面的项目从仓库中获取对应的配置信息的
先假设该项目使用的配置文件如下:
spring:
profiles:
active:
- dev
---
server:
port: 8001
spring:
profiles: dev
application:
name: microservicecloud-config-dept-client
datasource:
url: jdbc:mysql://localhost:3306/cloudDB01?useUnicode=true&characterEncoding=UTF-8&useSSL=true
username: root
password: root
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/
instance:
instance-id: microservicecloud-dept-8001
prefer-ip-address: true
---
server:
port: 8001
spring:
profiles: test
application:
name: microservicecloud-config-dept-client
datasource:
url: jdbc:mysql://localhost:3306/cloudDB02?useUnicode=true&characterEncoding=UTF-8&useSSL=true
username: root
password: root
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/
instance:
instance-id: microservicecloud-dept-8001
prefer-ip-address: true
并上传仓库
创建配置文件 bootstrap.yml
spring:
cloud:
config:
# 意思是通过 http://config-3345.com:3345 获取 master 分支下 microservicecloud-config-client 中的 test 环境的配置信息
name: microservicecloud-config-client
profile: test
label: master
uri: http://config-3345.com:3345
配置文件 application.yml 是用户级别的资源配置项,而 bootstrap.yml 是系统级别的,优先级要更高。所以在导入 application.yml 的时候已经 通过 http://config-3345.com:3345 获取了它指定的仓库中的 master 分支下的名称为 microservicecloud-config-client 的配置文件的 test 环境的配置信息。
配置文件 application.yml
spring:
application:
name: microservicecloud-config-client
其他的项目都如此操作,就可以实现通过仓库进行集中的修改配置文件,这个过程中如果所有的项目都添加了热部署,那么修改配置文件上传仓库之后可以达到实时更新无需重启服务的效果。