Spring Cloud Config(统一配置中心)
Spring Cloud Config
Spring Cloud Config为分布式系统中的外部化配置提供服务器和客户端支持。Spring Cloud Config 是一种用来动态获取Git、SVN、本地的配置文件的一种工具。可以在所有环境中管理应用程序的外部属性。可以与任何语言运行的任何应用程序一起使用。当应用程序通过部署从开发到测试并进入生产时,可以管理这些环境之间的配置,并确保应用程序具有迁移时需要运行的所有内容。服务器存储后端的默认实现使用git,可以轻松支持配置环境的标签版本,以及可用于管理内容的各种工具。添加替代实现并使用Spring配置插入很容易。
Github地址:https://github.com/spring-cloud/spring-cloud-config
官方指引:https://spring.io/projects/spring-cloud-config
Spring Cloud Config Server功能:
1.用于外部配置的HTTP,基于资源的API(名称 - 值对或等效的YAML内容)
2.加密和解密属性值(对称或非对称)
3.使用可轻松嵌入Spring Boot应用程序 @EnableConfigServer
Spring Cloud Config Client功能(适用于Spring应用程序):
1.绑定到Config Server
并Environment
使用远程属性源初始化Spring
2.加密和解密属性值(对称或非对称)
SpringBoot集成Spring Cloud Config统一配置中心
版本说明
SpringBoot:2.1.3.RELEASE
SpringCloud:Greenwich.SR1
引入Spring Cloud Config依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
这里使用Eureka注册中心,所以需要加上
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
配置很简单 只需要在启动类上加@EnableEurekaClient
开启Eureka客户端,@EnableConfigServer
开启统一配置中心
@SpringBootApplication
@EnableEurekaClient
@EnableConfigServer
public class SpringcloudConfigApplication {
public static void main(String[] args) {
SpringApplication.run(SpringcloudConfigApplication.class, args);
}
}
创建配置仓库
可以在私人Gitlab,码云,Github等等创建
我这里是在Github上创建的配置文件,一般都是yml
或者properties
配置文件
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
需要在项目的配置文件中指定连接的仓库,用户名和密码

spring.cloud.config.server.git.uri
就是仓库的访问地址
spring:
application:
name: config
cloud:
config:
server:
git:
uri: 项目配置仓库的位置,这个位置可以是:git文件夹、svn文件夹或者github项目位置,任何能访问到文件的地方。
username: 登录用户名
password: 登录密码
下面进行测试
先启动Eureka注册中心,在启动统一配置中心

在控制台可以看到 会在临时目录中创建一份配置文件
验证配置是否生效
在浏览器访问:http://localhost:8080/config-a.yml

官方提供http查看方式
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
application
:应用名 ,也就是spring.application.name
label
:分支名,默认master
profile
:环境名,环境可以在配置文件的属性名是env
或者spring.profiles.active
,不设置也可以