实现自定义的配置中心项目

除了配合后台管理页面的CRUD接口,本文主要介绍config服务的实现和client如何读取配置文件。

基于EnvironmentRepository

读取启动配置spring_cloud_config文件

1.配置中心项目端:

1)pom引入spring-cloud-config-server

2)实现EnvironmentRepository接口,重写findOne方法。

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里的接口读取启动配置文件

源码:
EnvironmentController#labelled 

  

2.客户端

1)pom引入pring-cloud-starter-config

2)bootstrap.yml配置配置中心项目地址:

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} 

源码
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

  

 

 

  

 

posted @ 2023-02-15 16:31  hy叶子  阅读(26)  评论(0编辑  收藏  举报