Spring Cloud Config服务端配置细节(一)

时间:2022-05-06
本文章向大家介绍Spring Cloud Config服务端配置细节(一),主要内容包括Git URI中的占位符、健康监测、安全保护、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

上篇文章我们看了Spring Cloud中分布式配置中心的一个基本使用,这里边还涉及到许多细节,本文我们就来看看服务端配置中的一些细节。


我们先通过下面一张图来看看Config Server的一个大致工作过程:

结合这张图,我来说如下五点:

1.首先我们需要一个远程的Git仓库,自己学习可以直接用GitHub,在在实际生产环境中,需要自己搭建一个Git服务器,远程Git仓库的作用主要是用来保存我们的配置文件 2.除了远程Git仓库之外,我们还需要一个本地Git仓库,每当Config Server访问远程Git仓库时,都会保存一份到本地,这样当远程仓库无法连接时,就直接使用本地存储的配置信息 3.至于微服务A、微服务B则是我们具体的应用,这些应用在启动的时候会从Config Server中来加载相应的配置信息 4.当微服务A/B尝试去从Config Server中加载配置信息的时候,Config Server会先通过git clone命令克隆一份配置文件保存到本地 5.由于配置文件是存储在Git仓库中,所以配置文件天然的具备版本管理功能,Git中的Hook功能可以实时监控配置文件的修改

Git URI中的占位符

灵活的使用URI占位符,可以有效的减少我们的工作量。考虑这样一个问题,我有ServerA、ServerB两个服务,两个服务对应的配置文件的存储地址分别位于https://github.com/lenve/scConfig/sa和https://github.com/lenve/scConfig/sb,但是我的Config Server只有一个,那么当我的ServerA和ServerB连接上Config Server时,Config Server怎么知道去哪个地址下拿配置文件?这个时候就涉及到占位符的使用。 在上篇文章中我们已经了解了Spring Cloud Config中的三种占位符,分别是{application}、{profile}和{label},这些占位符除了用来标识配置文件的规则,还可以用在Config Server中对Git仓库的URI配置,用在URI配置中时,这三个占位符的含义分别如下所示:

1.{application}映射到客户端的 spring.application.name 2.{profile}映射到客户端上的 spring.profiles.active 3.{label}这是一个服务器端功能,标记”版本”的配置文件集

此时,假设我不同环境下的配置文件分别放在下面这些目录下:

https://github.com/lenve/scConfig/app/dev https://github.com/lenve/scConfig/app/prod https://github.com/lenve/scConfig/app/test

那么我的客户端文件这样配置:

spring.application.name=app
# dev根据具体情况来修改
spring.cloud.config.profile=dev
spring.cloud.config.label=master
spring.cloud.config.uri=http://localhost:2007/
server.port=2008

然后Config Server按下面这种方式配置即可:

spring.cloud.config.server.git.uri=https://github.com/lenve/scConfig.git
spring.cloud.config.server.git.search-paths={application}/{profile}

当然这种存储规划不一定最佳,这里只是给小伙伴们演示占位符的用法。

默认情况下,Config Server 克隆下来的文件保存在C:Users<当前用户>AppDataLocalTemp目录下,我们可以通过如下配置来修改:

spring.cloud.config.server.git.basedir=E:\111\

健康监测

默认情况下Spring Cloud Config会为配置中心服务端创建一个健康监测器,该检测器默认情况下是访问的仓库文件是{application}为app的配置文件,如果仓库中不存在这个文件,健康显示器就会显示仓库无法连接,此时我们有两种解决方案:1.仓库中添加相应的配置文件;2.重新指定检测的配置,重新指定方式如下:

spring.cloud.config.server.health.repositories.check.name=app
spring.cloud.config.server.health.repositories.check.label=master
spring.cloud.config.server.health.repositories.check.profiles=dev

此时,系统回去访问http://localhost:2007/app/dev/master地址,如果能够访问到,则显示仓库已连接,如下:

安全保护

开发环境中我们的配置中心肯定是不能随随便便被人访问的,我们可以加上适当的保护机制,由于微服务是构建在Spring Boot之上,所以整合Spring Security是最方便的方式。

首先添加依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

然后在application.properties中配置用户名密码:

security.user.name=sang
security.user.password=123

最后在配置中心的客户端上配置用户名和密码即可,如下:

spring.cloud.config.username=sang
spring.cloud.config.password=123

OK,如此之后,其他人就不能随意的获取到我们的配置信息了。OK,本文就先说到这里,有问题欢迎留言讨论。

参考资料:

  1. 《Spring Cloud微服务实战》