查看原文
其他

跟我学Spring Cloud(Finchley版)-20-Spring Cloud Config-Git仓库配置详解

周立 IT牧场 2019-07-12

在 跟我学Spring Cloud(Finchley版)-19-配置中心-Spring Cloud Config 一节中,已实现使用Git仓库作为Config Server的后端存储,本节详细探讨如何配置Git仓库。

一、占位符支持

Config Server的占位符支持{application}、{profile}和{label}。

示例:

  1. server:

  2.  port: 8080

  3. spring:

  4.  application:

  5.    name: microservice-config-server

  6.  cloud:

  7.    config:

  8.      server:

  9.        git:

  10.          uri: https://git.oschina.net/itmuch/{application}

  11.          username:

  12.          password:

使用这种方式,即可轻松支持一个应用对应一个Git仓库。同理,也可支持一个profile对应一个Git仓库。

二、模式匹配

模式匹配指的是带有通配符的{application}/{profile}名称的列表。如果{application}/{profile}不匹配任何模式,它将会使用 spring.cloud.config.server.git.uri 定义的URI。

  1. spring:

  2.  cloud:

  3.    config:

  4.      server:

  5.        git:

  6.          uri: https://github.com/spring-cloud-samples/config-repo

  7.          repos:

  8.            simple: https://github.com/simple/config-repo

  9.            special:

  10.              pattern: special*/dev*,*special*/dev*

  11.              uri: https://github.com/special/config-repo

  12.            local:

  13.              pattern: local*

  14.              uri: file:/home/configsvc/config-repo

该例中,对于simple仓库,它只匹配所有配置文件中名为simple的应用程序,它的模式等同于 simple/* 。local仓库则匹配所有配置文件中以local开头的所有应用程序的名称。

三、搜索目录

很多场景下,我们可能把配置文件放在了Git仓库子目录中,此时可以使用search-paths指定,search-path同样支持占位符。

  1. spring:

  2.  cloud:

  3.    config:

  4.      server:

  5.        git:

  6.          uri: http://git.oschina.net/itmuch/spring-cloud-config-repo

  7.          search-paths: foo,bar*

这样,Config Server就会在Git仓库根目录、foo子目录、以及所有以bar开始的子目录中查找配置文件。

四、启动时加载配置文件

默认情况下,在配置被首次请求时,Config Server才会clone Git仓库。我们也可让Config Server在启动时就clone Git仓库,例如。

  1. spring:

  2.  cloud:

  3.    config:

  4.      server:

  5.        git:

  6.          uri: https://github.com/spring-cloud-samples/config-repo

  7.          repos:

  8.            team-a:

  9.                pattern:  microservice-*

  10.                clone-on-start: true

  11.                uri: http://git.oschina.net/itmuch/spring-cloud-config-repo

将属性 spring.cloud.config.server.git.repos.*.clone-on-start 设为true,即可让Config Server启动时clone指定Git仓库。

当然,也可使用 spring.cloud.config.server.git.clone-on-start=true 进行全局配置。

配置clone-on-start = true,可帮助Config Server启动时快速识别错误的配置源(例如无效的Git仓库)。

小技巧

将以下包的日志级别设为DEBUG,即可打印Config Server请求Git仓库的细节。我们可借助日志,更好地理解Config Server的Git仓库配置,同时,也便于我们快速定位问题。

  1. logging:

  2.  level:

  3.    org.springframework.cloud: DEBUG

  4.    org.springframework.boot: DEBUG

相关热文

干货分享

最近将个人学习笔记整理成册,使用PDF分享。关注我,回复如下代码,即可获得百度盘地址,无套路领取!

  • 001:《Java并发与高并发解决方案》学习笔记;

  • 002:《深入JVM内核——原理、诊断与优化》学习笔记;

  • 003:《Java面试宝典》

您的关注是对我最大的支持!


    您可能也对以下帖子感兴趣

    文章有问题?点此查看未经处理的缓存