Skip to content

Instantly share code, notes, and snippets.

@cmadsen
Last active February 3, 2016 16:53
Show Gist options
  • Save cmadsen/a84ee353154a841dae8e to your computer and use it in GitHub Desktop.
Save cmadsen/a84ee353154a841dae8e to your computer and use it in GitHub Desktop.
EurekaPropertySourceLocator
@Configuration
public class EurekaPropertySourceLocator implements PropertySourceLocator {
private static final Logger log = LoggerFactory
.getLogger(EurekaPropertySourceLocator.class);
@Override
public PropertySource<?> locate(Environment env) {
try {
String eurekaUrl = env.getProperty(
"eureka.instance.client.serviceUrldefaultZone");
log.debug("eurekaUrl {} ", eurekaUrl);
ResponseEntity<String> entity = new RestTemplate()
.getForEntity(eurekaUrl + "/apps", String.class);
JsonNode root = new ObjectMapper().readTree(entity.getBody());
// map eureka json for all vipAddress to spring environment ->
// vipAddress.host and vipAddress.port if multiple are found first
// is used
Map<String, Object> eurekaProps = toStream(
root.path("applications").path("application"))
.flatMap(n -> toStream(n.path("instance")))
.filter(i -> i.path("status").asText().equals("UP"))
.flatMap(this::vipHostAndPort)
.collect(toMap(e -> e.getKey(), e -> e.getValue(),
(first, second) -> first));
// http://stackoverflow.com/questions/27870136/java-lambda-stream-distinct-on-arbitrary-key
log.debug("eurekaProps={}", eurekaProps);
return new MapPropertySource("eurekaProperties", eurekaProps);
} catch (Exception e) {
log.error("", e);
}
return new MapPropertySource("eurekaProperties", new HashMap<>());
}
private Stream<Map.Entry<String, Object>> vipHostAndPort(JsonNode i) {
String vipAddress = i.path("vipAddress").asText();
return Stream.of(
entry(vipAddress + ".host", i.path("hostName").asText()),
entry(vipAddress + ".port", i.path("port").path("$").asText()));
}
private static Stream<JsonNode> toStream(JsonNode n) {
return StreamSupport.<JsonNode> stream(n.spliterator(), false);
}
private static Map.Entry<String, Object> entry(String key, Object value) {
return new AbstractMap.SimpleEntry<String, Object>(key, value);
}
}
@cmadsen
Copy link
Author

cmadsen commented Feb 3, 2016

Get eureka vip address host and port name as properties vipaddress.port and vipaddress.host

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment