Spring Cloud Config 学习(一)

简介

对于传统的单体应用,一般是使用配置文件来管理全部的配置,可是在微服务架构中,会存在不少的微服务,若是每个微服务都维护本身的配置,显然是很是的麻烦且不灵活,维护成本会很是高git

使用Spring Cloud Config能够实现一下功能github

  • 集中管理配置
  • 不一样环境,不一样配置
  • 运行时期动态调整。而且在修改配置时不会中止微服务
  • 配置修改后自动更新

Spring Cloud Config 为分布式系统外部化配置提供了服务器端和客户端的支持,它包括Config Server 和 Config Client 两部分。默认使用 Git 存储配置内容(也可使用Subversion、本地文件系统或 Vault 存储配置)。Config Client 会在微服务启动时,请求 Config Server 以获取所须要的配置属性,而且缓存在本地以提升性能。spring

图片描述

图片来源缓存

实践

Config Server

准备Git仓库

这里须要一个Git仓库来存储配置文件,我是使用GitHub来作仓库的。须要在仓库的根目录下放置几个测试用的配置文件服务器

clipboard.png

文件:架构

microservice-foo.properties
microservice-foo-dev.properties
microservice-foo-test.properties
microservice-foo-production.properties

内容分别是:app

profile=default-1.0
profile=dev-1.0
profile=test-1.0
profile=production-1.0

而后新建分支dev ,而且将 microservice-foo-dev.properties 文件中的内容修改成 profile=dev-2.0分布式

编写代码

集成:微服务

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>

启动文件添加@EnableConfigServer标签性能

配置文件:

spring.application.name=microservice-config-server

# 这个uri使用能够clone的路径
spring.cloud.config.server.git.uri=https://github.com/wkkdhr/Dome1.git
# github的帐号密码
spring.cloud.config.server.git.username=***
spring.cloud.config.server.git.password=***

启动服务以后,就可使用 Config Service 的端点获取配置文件内容了。配置文件与端点的映射规则以下:

/{application}/{profile}/{label}

/{application}-{profile}.yml
/{application}-{profile}.properties

/{label}/{application}-{profile}.yml
/{label}/{application}-{profile}.properties

占位符含义:

  • {application} 表示微服务名称。microservice-foo-dev.properties 中 microservice-foo 就是微服务名称
  • {profile} 表示微服务名后面的dev、test等。microservice-foo-dev.properties 中 dev 就是{profile}
  • {label} 表示Git仓库分支,默认是master,可省略

访问 http://localhost:8080/microservice-foo/dev 获得如下结果:

clipboard.png

能够看到相关的配置详情信息。

访问 http://localhost:8080/microservice-foo-dev.properties 能够直接获取配置文件内容:

clipboard.png

须要说明一下,由于是使用GitHub来做为Git仓库,因此访问有可能会出现失败的风险

相关文章
相关标签/搜索