Spring Cloud 框架 -- Spring Cloud Config

Spring Cloud Config 介绍

Spring Cloud Config 是分布式配置中心解决方案。它包含了 Client 和 Server 。配置文件放在 Server 端,通过接口的形式提供给 Client .

Spring Cloud Config 主要功能:

  • 集中管理各个环境,各个微服务的配置文件

  • 提供服务端和客户端支持

  • 配置文件修改后,可以快速生效

  • 配置文件通过 Git/SVN 进行管理,天然支持版本回退功能

  • 支持高并发查询,也支持多种开发语言。

准备工作

准备工作主要是给 GitHub 上提交数据。

先在 GitHub 上,新建仓库 configRepo

再在本地新建文件夹 configRepo,

在文件夹 configRepo 内,新建文件夹 client1

在文件夹 client1 内,新建三个 properties 文件:

分别写入如下内容:

you=dev
you=prod
you=test

代表三个不同环境下的配置文件。

在文件夹 configRepo 内,右键打开 Git bash here ,操作如下:

git init
git add .
git commit -m "first commit"
git remote add origin https://github.com/youlinwei/configRepo.git
git push -u origin master

打开https://github.com/youlinwei/configRepo,就可以查看到提交上去的 client1 文件夹:

ConfigServer

ConfigServer 会自动从 GitHub 上加载配置文件,再以接口的形式提供给 ConfigClient 。

首先创建一个 ConfigServer 工程,创建时添加 ConfigServer 依赖:

项目创建成功后,在启动类上添加注解,开启 config server 功能:

@SpringBootApplication
@EnableConfigServer
public class ConfigserverApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConfigserverApplication.class, args);
    }

}

然后在配置文件中配置仓库的基本信息:

spring.application.name=config-server
server.port=8081
# 配置文件仓库地址
spring.cloud.config.server.git.uri=https://github.com/youlinwei/configRepo.git
# 仓库中,配置文件的目录
spring.cloud.config.server.git.search-paths=client1
# 仓库的用户名和密码
spring.cloud.config.server.git.username=1476219151@qq.com
spring.cloud.config.server.git.password=xxxxxx

启动项目,就可以访问配置文件了,访问地址如:http://localhost:8081/client1/dev/master,效果如下:

实际上,访问地址有如下规则:

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

application 表示配置文件名
profile 表示配置文件profile,例如test、dev、prod
lable 表示 git 分支,默认是 master

接下来,可以修改配置文件,并且重新提交到 GitHub ,此时,刷新 configserver 接口,就可以看到最新的配置内容。

posted @ 2021-06-15 17:03  爱吃西瓜的番茄酱  阅读(153)  评论(0编辑  收藏  举报