前言:本文的 Config 集中化的配置 主要技术内容学习自教程视频:https://www.bilibili.com/video/BV1jJ411S7xr?p=18,此教程非常通俗易懂且有质量,也希望更多人能够支持这样高质量的UP,我在学习时收获很多,因视频形式不易复习回顾,因此加了一部分自己的见解并整理成图文博客的形式。

文章目录

  • ​​1 引出 Spring Cloud Config​​
  • ​​2 Config 介绍​​
  • ​​3 Config 的工作模式​​
  • ​​4 项目实战​​
  • ​​4.1 服务端连接 Git 配置​​
  • ​​4.2 客户端连接服务端远程访问​​

1 引出 Spring Cloud Config

分布式系统面临的–配置文件的问题:

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_spring cloud


由此,出现了 Spring Cloud Config ,为简化描述,下文用 Config 代替 Spring Cloud Config 的表述

2 Config 介绍

官方文档的介绍:

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_服务端_02

3 Config 的工作模式

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_服务端_03


【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_java_04

4 项目实战

4.1 服务端连接 Git 配置

0、事先建好远程仓库

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_spring_05


包含的配置文件信息

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_服务端_06

1、新建子模块 springcloud-config-server-3344 ,pom 添加依赖

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_服务端_07

2、编写 yml 配置

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_spring_08


3、编写启动类

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_服务端_09


4、启动项目,进行测试官方文档给出了访问 yml 的请求格式

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_java_10

访问

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_java_11


请求进行了重定向,url如下(注:直接访问此url会报错Error Page)

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_git_12

访问

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_spring cloud_13


(这次请求就没有重定向,是因为之前dev是当前激活的原因吗?暂时没懂这里)

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_服务端_14

4.2 客户端连接服务端远程访问

1、编写客户端所需的 yml 配置

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_服务端_15


2、更新至远程 Git 仓库

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_服务端_16


【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_java_17


3、新建子模块 springcloud-config-client-3355 ,pom 添加依赖

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_spring cloud_18

2、编写 yml 配置

(将系统级配置和用户级配置分开写)

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_git_19

3、编写配置类和启动类

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_spring_20


【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_java_21


4、测试

先保证 Config 的服务模块能成功拿取到配置信息,再去测试 Config 的客户模块

测试 config-server

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_spring cloud_22


测试 config-client(这里 url 为我们在 controller 中配置的请求映射,可看到,@Value 注解成功读出服务模块中在远程拉去的配置信息,将值注入给了属性)

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_spring_23


之后,我们将系统配置 yml 文件的当前环境设为 test

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_spring_24


访问

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_spring_25

因此,总结一下,Spring Cloud Config 使得客户模块只需从 Config 服务模块去拿取自己的配置,而 Config 服务模块自己去远程 Git 仓库中拿取配置,Config 服务模块指明远程 Git 仓库的地址,Config 客户模块指明其中具体的配置文件名

【Spring Cloud】Config 集中化的配置:介绍、工作模式、项目实战_git_26