Spring-BootSpringBoot极简教程 · Spring Boot

跟我学Spring Cloud(Finchley版)-19-配置

2019-01-31  本文已影响17人  周立_itmuch

经过前文讲解,至此,微服务架构已经日趋完善——现在已经可以做一个大型的应用了!然而,随着项目的迭代,微服务数目往往与日俱增,如何高效地管理配置成为我们必须解决的问题。本节来讨论如何使用Spring Cloud Config管理配置。

为什么要使用配置中心

Spring Cloud Config简介

Spring Cloud Config为分布式系统外部化配置提供了服务器端和客户端的支持,它包括Config Server和Config Client两部分。由于Config Server和Config Client都实现了对Spring Environment和PropertySource抽象的映射,因此,Spring Cloud Config非常适合Spring应用程序,当然也可与任何其他语言编写的应用程序配合使用。

Config Server是一个可横向扩展、集中式的配置服务器,它用于集中管理应用程序各个环境下的配置,默认使用Git存储配置内容(也可使用Subversion、MySQL、本地文件系统或Vault存储配置,本博客以Git为例进行讲解),因此可以很方便地实现对配置的版本控制与内容审计。

Config Client是Config Server的客户端,用于操作存储在Config Server中的配置属性。引入Spring Cloud Config后的架构如下:

Spring Cloud Config架构图

TIPS

Spring Cloud Config的GitHub:https://github.com/spring-cloud/spring-cloud-config

编写Config Server

示例

路径规则

Spring Cloud Config Server提供了RESTful API,可用来访问存放在Git仓库中的配置文件。

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

其中的{appliation}、{profile}、{label} 都是占位符。

TIPS

事实上,可使用Spring Cloud Config实现配置的“继承”与“组合”,举个例子——

假设有一个应用:microservice-foo ,其profile是dev,那么其实Spring Cloud Config会查找如下几个文件:

对于相同属性的配置,从上至下优先级逐渐递减;最终获得的配置属性是四个文件的组合。由此,不难分析,可如下规划几个配置文件:

测试

集成Config Client

编码

测试

访问http://localhost:8081/profile 可返回Git仓库中的配置属性。

配套代码

Config Server

Config Client

本文首发

http://www.itmuch.com/spring-cloud/finchley-19/

干货分享

全是干货哦!
上一篇 下一篇

猜你喜欢

热点阅读