Spring Cloud Config
Spring Cloud Config为分布式系统中的外部配置提供服务器和客户端支持。使用Config Server,您可以在所有环境中管理应用程序的外部属性。客户端和服务器上的概念映射与Spring Environment和PropertySource抽象相同,因此它们与Spring应用程序非常契合,但可以与任何以任何语言运行的应用程序一起使用。随着应用程序通过从开发人员到测试和生产的部署流程,您可以管理这些环境之间的配置,并确定应用程序具有迁移时需要运行的一切。服务器存储后端的默认实现使用git,因此它轻松支持标签版本的配置环境,以及可以访问用于管理内容的各种工具。可以轻松添加替代实现,并使用Spring配置将其插入。
项目介绍
项目地址 :https://gitee.com/fw_spring/springCloudConfigDemo
Spring Cloud Config 服务democonfig-server 配置服务端,服务管理配置信息;
config-client 客户端,客户端调用server端暴露接口获取配置信息
相关知识点梳理
pom.xml
+ spring-boot-starter-parent //Spring Boot的父级依赖
+ spring-cloud-dependencies //版本依赖
+ spring-cloud-starter-config
+ spring-cloud-config-server
特征
Spring Cloud Config Server功能:
用于外部配置的HTTP,基于资源的API(名称-值对或等效的YAML内容)
加密和解密属性值(对称或非对称)
使用可轻松嵌入Spring Boot应用程序 @EnableConfigServer
Config Client功能(适用于Spring应用程序):
绑定到Config Server并Environment使用远程属性源初始化Spring
加密和解密属性值(对称或非对称)
spring.cloud.config.uri在bootstrap.[yml | properties]中配置、通过系统属性或环境变量中设置。
获取git上的资源信息遵循如下规则
>> /{application}/{profile}[/{label}]
>> /{application}-{profile}.yml
>> /{label}/{application}-{profile}.yml
>> /{application}-{profile}.properties
>> /{label}/{application}-{profile}.properties
application:表示应用名称,在client中通过spring.cloud.config.name配置,缺省时默认sprin.application.name的值
profile:表示获取指定环境下配置,例如开发环境、测试环境、生产环境 默认值default,实际开发中可以是 dev、test、demo、production等
label: git标签,默认值master
服务端说明
server:
port: 3200
spring:
application:
name: fw-server-config
cloud:
config:
server:
git:
uri: https://gitee.com/fw_spring/config_repo # 配置git仓库的地址
# search-paths: config_repo # git仓库地址下的相对地址,可以配置多个,用,分割。
username: *** # git仓库的账号
password: *** # git仓库的密码
label: master
客户端说明
spring:
application:
name: config-client
cloud:
config:
#name: fw-service-provider #应用名称,默认与spring.application.name相同
#profile: default #环境名称,默认default
#label: master #分支名称,默认master
#uri: http://localhost:3200 #spring cloud config服务地址
discovery:
#表示使用服务发现组件中的Config Server
enabled: true
#指定Config Server在服务发现中的serviceId
service-id: fw-server-config
注意这里是bootstrap.yml而不是appliction.yml,因为bootstrap.yml会在应用启动之前读取, 而
spring.cloud.config.uri
会影响应用启动.
自动刷新数据(配合Spring Cloud Bus使用, 待验证)
- 客户端引入 spring-boot-starter-actuator(Spring Boot Actuator,感应服务端变化)
- 加入@RefreshScope 可以动态刷新这个Bean
- 调用/refresh接口,注意这里要用post方法进行访问, 触发刷新
将配置中心注册到服务发现
- 添加
@EnableEurekaClient
注解- 在pom.xml中引用
spring-cloud-starter-eureka
- application.yml中添加 如下内容
#注册中心
eureka:
client:
serviceUrl:
defaultZone: http://localhost:3100/eureka/
instance:
prefer-ip-address: true
通过服务发现连接配置中心(客户端)
- 添加
@EnableEurekaClient
注解- 在pom.xml中引用
spring-cloud-starter-eureka
- bootstrap.yml中添加 如下内容
spring:
application:
name: fw-config
cloud:
config:
#name: fw-config-dev
#profile: default
#label: master
#uri: http://localhost:3200
discovery:
#表示使用服务发现组件中的Config Server
enabled: true
#指定Config Server在服务发现中的serviceId
service-id: spring-cloud-config-server
#注册中心
eureka:
client:
serviceUrl:
defaultZone: http://localhost:3100/eureka/
instance:
prefer-ip-address: true