一、配置中心提供的核心功能
Spring Cloud Config为服务端和客户端提供了分布式系统的外部化配置支持。配置服务器为各应用的所有环境提供了一个中心化的外部配置。它实现了对服务端和客户端对Spring Environment和PropertySource抽象的映射
Spring Cloud Config项目是一个解决分布式系统的配置管理方案。它包含了Client和Server两个部分,server提供配置文件的存储、以接口的形式将配置文件的内容提供出去,client通过接口获取数据、并依据此数据初始化自己的应用。
Spring cloud使用git或svn存放配置文件,当然他也提供本地化文件系统的存储方式,默认情况下使用git。
二、构建Config Server
分为三步:
1.pom.xml中引入spring-cloud-config-server
依赖:
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> </dependencies>
2.启动类添加@EnableConfigServer注解,激活对配置中心的支持
@EnableConfigServer @SpringBootApplication public class ConfigServerApplication { public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); } }
3.配置文件
Git配置:(开发,测试,生产三份文件)
server:
port: 8001
spring:
application:
name: spring-cloud-config-server
cloud:
config:
server:
git:
uri: https: # 配置git仓库的地址
search-paths: # git仓库地址下的相对地址,可以配置多个,用,分割。
username: # git仓库的账号
password: # git仓库的密码
svn配置: (和git版本稍有区别,需要显示声明subversion.)
server:
port: 8001
spring:
cloud:
config:
server:
svn:
uri: http://192.168.0.6/svn/repo/config-repo
username: username
password: password
default-label: trunk
profiles:
active: subversion
application:
name: spring-cloud-config-server
本地存储配置的方式:(只需设置属性)
spring.profiles.active=native
,
Config Server会默认从应用的src/main/resource
目录下检索配置文件。也可以通过spring.cloud.config.server.native.searchLocations=file:F:/properties/
属性来指定配置文件的位置。
虽然Spring Cloud Config提供了这样的功能,但是为了支持更好的管理内容和版本控制的功能,还是推荐使用git的方式。
4.测试:
github创建了一个config-repo目录作为配置仓库,并根据不同环境新建了下面四个配置文件:
- didispace.properties
- didispace-dev.properties
- didispace-test.properties
- didispace-prod.properties
其中设置了一个from属性,为每个配置文件分别设置了不同的值,如:
- from=git-default-1.0
- from=git-dev-1.0
- from=git-test-1.0
- from=git-prod-1.0
URL与配置文件的映射关系如下:
- /{application}/{profile}[/{label}]
- /{application}-{profile}.yml
- /{label}/{application}-{profile}.yml
- /{application}-{profile}.properties
- /{label}/{application}-{profile}.properties
上面的url会映射{application}-{profile}.properties
对应的配置文件,{label}
对应git上不同的分支,默认为master。
测试server端是否可以读取到github上面的配置信息,直接访问:
{ "name": "", "profiles": ["dev"], "label": null, "version": "", "state": null, "propertySources": [{ "name": "dev.yml", "source": { "debug": false, "server.port": 8001, } }] }
续、、
参考:http://www.ityouknow.com/springcloud/2017/05/22/springcloud-config-git.html