原创 

spring cloud 根据profile 配置拉取其他服务配置(spring cloud 配置拉取实现)

分类:spring,java    296人阅读    IT小君  2023-03-24 23:23

需求场景:有时需要拉取其他服务(非本服务)的配置进行一些操作

原理:

我们都知道Spring Cloud Config Server 可以通过以下格式拉取配置信息:

/{application}/{profile}[/{label}]

/{application}-{profile}.yml

/{label}/{application}-{profile}.yml

/{application}-{profile}.properties

/{label}/{application}-{profile}.properties

所以我们只需要生成这个对应url就好,

application:作为参数传入

profile、label:读取环境对应配置

 

代码如下:

以下代码来源于spring cloud 拉取配置信息的源代码改造

@Autowired
private ConfigClientProperties properties;

public Map < String, String > fetchMongoConfig(string serviceName) {
        Map < String, String > result = new HashMap < > ();
        RestTemplate restTemplate = this.getSecureRestTemplate(this.properties);
        String[] labels = new String[]("");
        if (org.springframework.util.Stringutils.hasText(this.properties.getLabel())){
                labels = org.springframework.util.Stringutils.commaDelimitedlistToStringArray(this.properties.getlabel()):
        }
                String state = ConfigCllentStateHolder.getState(); 
                String[] var4 = labels; 
                int var5 = labels.length;
                for (int yar6 = 0; var6 < var5; ++yar6) {
                    String label = var4[yar6];
                    Environment env = this.getRemoteEnvironment(restTemplate, this.properties, label.trim(), state, servicename);
                    env.getPropertySources().forEach(item - > {
                                Map < String, String > config = (Map<String, String>)item.getSource();
                                Logger.error("item.getName(): " + item.getName());
                                if (item.getName().contains(serviceName)) {
                                        result.put("ip",config.get("spring.data.mongodb .host"));
                                        result.put("port",String.valueOf(config.get("spring.data.mongadb.port")));
                                        result.put("password",config.get("spring.data.mongadb.passward"));
                                        result.put("username",config.get("spring.data.mongodb.username"));
                                        result.put("database", config.get("spring,data.mongodb.database"));
                                }
                         });
                }
                return result;
}


private Environment getRemoteEnvironment(RestTemplate restTemplate, ConfigClientProperties properties, String label, String state, String name) {
    String path = "/{name}/{profile}";
    String profile = properties.getProfile();
    String token = properties.getToken();
    String uri = properties.getRawUri();
    Object[] args = new String[] {
        name, profile
    };
    if (org.springframework.util.StringUtils.hasText(label)) {
        args = new String[] {
            name, profile, label
        };
        path = path + "/{label}";
    }
    ResponseEntity response = null;
    try {
        HttpHeaders headers = new HttpHeaders();
        if (org.springframework.util.StringUtils.hasText(token)) {
            headers.add("X-Config-Token", token);
        }
        if (org.springframework.util.StringUtils.hasText(state)) {
            headers.add("X-Config-State", state);
        }
        HttpEntity < Void > entity = new HttpEntity((Void) null, headers);
        logger.error(uri + path);
        response = restTemplate.exchange(uri + path, HttpMethod.GET, entity, Environment.class, args);
    } catch (HttpClientErrorException var14) {
        if (var14.getStatusCode() != HttpStatus.NOT_FOUND) {
            throw var14;
        }
    }
    if (response != null && response.getStatusCode() == HttpStatus.OK) {
        Environment result = (Environment) response.getBody();
        return result;
    } else {
        return null;
    }
}

private RestTemplate getSecureRestTemplate(ConfigClientProperties client) {
    SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    requestFactory.setReadTimeout((60 * 1000 * 3) + 5000);
    //TODO 3m5s, make configurable? 
    RestTemplate template = new RestTemplate(requestFactory);
    String username = client.getUsername();
    String password = client.getPassword();
    String authorization = client.getAuthorization();
    Map < String, String > headers = new HashMap < > (client.getHeaders());
    if (password != null && authorization != null) {
        throw new IllegalStateException("You must set either 'password' or 'authorization'");
    }
    if (password != null) {
        byte[] token = Base64Utils.encode((username + ":" + password).getBytes());
        headers.put("Authorization", "Basic " + new String(token));
    } else if (authorization != null) {
        headers.put("Authorization", authorization);
    }
    if (!headers.isEmpty()) {
        template.setInterceptors(Arrays. < ClientHttpRequestInterceptor > asList(new ConfigServicePropertySourceLocator.GenericRequestHeaderInterceptor(headers)));
    }
    return template;
}

点击广告,支持我们为你提供更好的服务

canvas炫酷鼠标移动文字粒子特效

html5 canvas进度条圆环图表统计动画特效

响应式咖啡饮品宣传网站模板

HTML5数字产品服务公司网站模板

现代时尚家具公司网站模板

响应式时尚单品在线商城网站模板

网页设计开发公司网站模板

有机水果蔬菜HTML5网站模板

html5图标下拉搜索框自动匹配代码

css鼠标跟随文字模糊特效

css+js实现的颜色渐变数字时钟动画特效

html5 svg夜空中星星流星动画场景特效

中小型创意设计服务公司网站模板

HTML5现代家居装潢公司网站模板

HTML5 Canvas竖直流动线条背景动画特效

js+css3抽奖转盘旋转点餐代码

响应式太阳能能源公司网站模板

小众时尚单品在线电子商务网站模板

jQuery右端悬浮带返回顶部特效

html5 canvas彩色碎片组合球形旋转动画特效

点击广告,支持我们为你提供更好的服务
 工具推荐 更多»
点击广告,支持我们为你提供更好的服务