需求场景:有时需要拉取其他服务(非本服务)的配置进行一些操作
原理:
我们都知道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;
}