实现自定义的配置中心项目
除了配合后台管理页面的CRUD接口,本文主要介绍config服务的实现和client如何读取配置文件。
基于EnvironmentRepository
读取启动配置spring_cloud_config文件
1.配置中心项目端:
1)pom引入spring-cloud-config-server
2)实现EnvironmentRepository接口,重写findOne方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import org.springframework.cloud.config.server.environment.EnvironmentRepository; public class ConfigEnvironmentRepository implements EnvironmentRepository, Ordered { @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } @Override public Environment findOne(String application, String profile, String label) { Environment env = new Environment(application, new String[]{profile}, label, version, null ); //获得content ,自定义是查询数据库还是读取git // 解析yml if (StringUtils.isNotBlank(content)) { final String name = application + "-" + label; final Map<String, Object> source = SpringYamlLoader.yaml2Map(name, content); env.add( new PropertySource(name, source)); } return env; } } |
3)客户端调用的是EnvironmentController里的接口读取启动配置文件
源码:
1 | EnvironmentController#labelled |
2.客户端
1)pom引入pring-cloud-starter-config
2)bootstrap.yml配置配置中心项目地址:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | config_server: dev: test: pre: prd: DEPLOY_ENV: test spring: application: name: xxx cloud: config: uri: ${config_server.${DEPLOY_ENV}} label: ${DEPLOY_ENV} |
3)spring cloud项目启动时调用以下接口读取配置 /{name}/{profiles}/{label}
spring底层启动调用了接口/{name}/{profile}/{label}
源码
1 2 3 4 5 6 | PropertySourceBootstrapConfiguration#initialize 实现了ApplicationContextInitializer初始化器接口 ConfigServicePropertySourceLocator#locate ConfigServicePropertySourceLocator#getRemoteEnvironment restTemplate.exchange(uri + path, HttpMethod.GET, entity,Environment. class , args) path = /{name}/{profile}/{label} http: //url:port/name/default/test |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)