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 接口,就可以看到最新的配置内容。
【推荐】100%开源!大型工业跨平台软件C++源码提供,建模,组态!
【推荐】AI 的力量,开发者的翅膀:欢迎使用 AI 原生开发工具 TRAE
【推荐】2025 HarmonyOS 鸿蒙创新赛正式启动,百万大奖等你挑战
· 通过 Canvas 将后端发来的一帧帧图片渲染成“视频”的实现过程
· 当加密ID需要变成Guid:为什么我选择了AES-CBC而非GCM?
· 基于 epoll 的协程调度器——零基础深入浅出 C++20 协程
· 下划线字段在golang结构体中的应用
· SQL Server也能玩正则表达式?
· C#实现屏幕墙:同时监控多个电脑桌面(支持Windows、信创Linux、银河麒麟、统信UOS)
· 直击痛点的开源项目「GitHub 热点速览」
· C# 13 与 .NET 9 跨平台开发实战(第一章:开发环境搭建与.NET概述-上篇)
· 我的AI自学路线,可能对你有用
· 记一次 .NET 某自动化智能制造软件 卡死分析