Merge pull request #287 from knalx/master

* pull287:
  Fixes ipv6 formatting for consul discovery.
This commit is contained in:
Spencer Gibb
2017-03-07 10:49:52 -07:00
2 changed files with 50 additions and 2 deletions

View File

@@ -16,6 +16,9 @@
package org.springframework.cloud.consul.discovery;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
@@ -29,6 +32,7 @@ import lombok.extern.apachecommons.CommonsLog;
/**
* @author Spencer Gibb
* @author Semenkov Alexey
*/
@CommonsLog
public class ConsulServerUtils {
@@ -38,13 +42,27 @@ public class ConsulServerUtils {
HealthService.Node node = healthService.getNode();
if (StringUtils.hasText(service.getAddress())) {
return service.getAddress();
return fixIPv6Address(service.getAddress());
} else if (StringUtils.hasText(node.getAddress())) {
return node.getAddress();
return fixIPv6Address(node.getAddress());
}
return node.getNode();
}
public static String fixIPv6Address(String address) {
try {
InetAddress inetAdr = InetAddress.getByName(address);
if (inetAdr instanceof Inet6Address) {
return "[" + inetAdr.getHostName() + "]";
}
return address;
} catch (UnknownHostException e) {
log.debug("Not InetAddress: " + address + " , resolved as is.");
return address;
}
}
public static Map<String, String> getMetadata(HealthService healthService) {
return getMetadata(healthService.getService().getTags());
}

View File

@@ -0,0 +1,30 @@
package org.springframework.cloud.consul.discovery;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author Semenkov Alexey
*/
public class ConsulServerUtilsTest {
@Test
public void testAddressFormat() {
String s1 = ConsulServerUtils.fixIPv6Address("fc00:ec:cd::242:ac11:c");
assertEquals("[fc00:ec:cd:0:0:242:ac11:c]", s1);
String s2 = ConsulServerUtils.fixIPv6Address("[fc00:ec:cd::242:ac11:c]");
assertEquals("[fc00:ec:cd:0:0:242:ac11:c]", s2);
String s3 = ConsulServerUtils.fixIPv6Address("192.168.0.1");
assertEquals("192.168.0.1", s3);
String s4 = ConsulServerUtils.fixIPv6Address("projects.spring.io");
assertEquals("projects.spring.io", s4);
String s5 = ConsulServerUtils.fixIPv6Address("veryLongHostName");
assertEquals("veryLongHostName", s5);
}
}