Spring-Cloud-Config 共享公共配置

来源:互联网 发布:楼月软件 编辑:程序博客网 时间:2024/05/21 13:30

本文不是讲 Spring-Cloud-Config-Server / Spring-Cloud-Config-Client 怎么使用的。

这里说的 客户端 是指:Spring-Cloud-Config 的客户端。

零、问题描述

基于 Spring-Cloud 技术栈进行开发时,通常会配一个 Spring-Cloud-Config-Server,各个 客户端 通过 Spring-Cloud-Config-Server配置仓库 拉取自己服务的配置。

假设客户端 service-a 对应的配置文件为 service-a.yml,客户端 service-b 对应的配置文件为 service-b.yml,如果 service-aservice-b 都需要使用同一个数据源配置,岂不是要在 service-a.ymlservice-b.yml 中同一个数据源配置写两遍?

重复意味着容易出错和那以维护。

目前我能搜罗到的方案有两种,示例中暂不考虑环境 profile 的情况(实际使用时对应加上 profile 即可)

一、方案一

配置仓库根目录application.ymlSpring-Cloud-Config-Server 支持这种方式。

详见官方文档:Sharing Configuration With All Applications

当我们使用 Quick Start 中的那些 endpoint 访问时会发现,全局的配置 会与 客户端独有的配置合并。

二、方案二

公共的配置文件独立出来,客户端在 spring.application.name 中多指定一个公共配置的名称(理论上在 spring.profiles.include 指定包括公共配置的名称也是可以的)。

比如在 配置仓库 根目录下创建一个 datasorce.yml 公共配置文件用来存放数据源配置,然后在各个客户端的 bootstap.yml 配置文件中指定。

例如:

service-a 客户端的 bootstap.yml

spring:  application:    name: service-a, datasorce

service-b 客户端的 bootstap.yml

spring:  application:    name: service-b, datasorce

理论上在 spring.profiles.include 指定包括公共配置的名称也是可以的,未测试结果不详

例如:

service-a 客户端的 bootstap.yml

spring:  application:    name: service-a  profiles:    include: datasorce

service-b 客户端的 bootstap.yml

spring:  application:    name: service-b  profiles:    include: datasorce

四、参考资料

  • Sharing Configuration With All Applications
  • Add spring-cloud-config-server ability to share common configuration across applications
  • loading multiple properties with config-server
原创粉丝点击