1 前言
可配置是一个成熟软件系统应该提供的特性,而配置管理对于大型系统就显得十分重要,特别是对于拥有多个应用的微服务系统。可喜的是,Spring为我们提供了很好的配置管理,如Springboot的配置就很强大。对于Spring Cloud,就有强大的Spring Cloud Config,在提供了一个在应用之外的配置管理,如文件或Git仓库,对分布式系统配置管理十分有益。
2 快速体验
Spring Cloud Config服务端就是一个Springboot应用,启动、部署都十分简单。
整体的架构如下图所示:
2.1 服务端就是一个Springboot
在Springboot中添加依赖如下:
org.springframework.cloud
spring-cloud-config-server
2.2.0.RELEASE
只需要一个就行了,它已经包含了web和actuator。
添加Java主类:package com.pkslow.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
@EnableConfigServer
public class ConfigServer {
public static void main(String[] args) {
SpringApplication.run(ConfigServer.class,args);
}
}
跟普通的Springboot应用相比只是多了一个注解@EnableConfigServer而已。
2.2 配置仓库
通过我们会把配置通过版本控制管理起来,一般使用Git仓库,为简单展示使用本地仓库如下:# 创建目录
mkdir git-repo
# 初始化一个git目录
git init
# 新建文件
touch application.properties
# 添加变更
git add .
# 提交变更
git commit -m "init"
配置一下项目的application.properties,注意是Config Server项目的,而不是在git-repo目录里的:server.port=8888
spring.application.name=config-server
spring.cloud.config.server.git.uri=/Users/pkslow/IdeaProjects/pkslow-modules/config-server/git-repo
接着就可以启动Config Server了。
但git仓库里的配置文件没有什么内容,我们加入以下内容并提交(必须要提交,不然无法获取)。pkslow.webSite=www.pkslow.com
pkslow.age=18
pkslow.email=admin@pkslow.com
2.3 配置路径匹配
那我们如何获取这些配置呢?可以通过以下URL读取:/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.propertieslabel指的是代码分支,如master,feature-1等。
application是应用的名字,在以后客户端读取会用到。
profile一般用于指定环境,如prod,dev,uat等。
所以,我们可以用以下URL来获取我们刚添加的配置信息:http://localhost:8888/application/default
http://localhost:8888/application/default/master
http://localhost:8888/master/application.properties
http://localhost:8888/application-default.properties
访问如下:$ curl http://localhost:8888/application/default/master
{"name":"application","profiles":["default"],"label":"master","version":"8796f39b35095f6e9b7176457eb03dd6d62b1783","state":null,"propertySources":[{"name":"/Users/pkslow/IdeaProjects/pkslow-modules/config-server/git-repo/application.properties","source":{"pkslow.webSite":"www.pkslow.com","pkslow.age":"18","pkslow.email":"admin@pkslow.com"}}]}
最后一个地址/{label}/{application}-{profi