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 接口,就可以看到最新的配置内容。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档
· 软件产品开发中常见的10个问题及处理方法