问题场景: 服务器中有两个网卡假设IP为 十、13这两个开头的 13这个是可使用的,10这个是不能使用 在这种状况下,服务注册时Eureka Client会自动选择10开头的ip为做为服务ip, 致使其它服务没法调用。正则表达式
问题缘由(参考别人博客得知):因为官方并无写明Eureka Client探测本机IP的逻辑,因此只能翻阅源代码。Eureka Client的源码在eureka-client模块下,com.netflix.appinfo包下的InstanceInfo类封装了本机信息,其中就包括了IP地址。在 Spring Cloud 环境下,Eureka Client并无本身实现探测本机IP的逻辑,而是交给Spring的InetUtils工具类的findFirstNonLoopbackAddress()方法完成的:spring
public InetAddress findFirstNonLoopbackAddress() {
InetAddress result = null;
try {
// 记录网卡最小索引
int lowest = Integer.MAX_VALUE;
// 获取全部网卡
for (Enumeration<NetworkInterface> nics = NetworkInterface
.getNetworkInterfaces(); nics.hasMoreElements();) {
NetworkInterface ifc = nics.nextElement();
if (ifc.isUp()) {
log.trace("Testing interface: " + ifc.getDisplayName());
if (ifc.getIndex() < lowest || result == null) {
lowest = ifc.getIndex(); // 记录索引
}
else if (result != null) {
continue;
}
// @formatter:off
if (!ignoreInterface(ifc.getDisplayName())) { // 是不是被忽略的网卡
for (Enumeration<InetAddress> addrs = ifc
.getInetAddresses(); addrs.hasMoreElements();) {
InetAddress address = addrs.nextElement();
if (address instanceof Inet4Address
&& !address.isLoopbackAddress()
&& !ignoreAddress(address)) {
log.trace("Found non-loopback interface: "
+ ifc.getDisplayName());
result = address;
}
}
}
// @formatter:on
}
}
}
catch (IOException ex) {
log.error("Cannot get first non-loopback address", ex);
}
if (result != null) {
return result;
}
try {
return InetAddress.getLocalHost(); // 若是以上逻辑都没有找到合适的网卡,则使用JDK的InetAddress.getLocalhost()
}
catch (UnknownHostException e) {
log.warn("Unable to retrieve localhost");
}
return null;
}
复制代码
解决方案:bash
一、忽略指定网卡服务器
经过上面源码分析能够得知,spring cloud确定能配置一个网卡忽略列表。经过查文档资料得知确实存在该属性:app
spring.cloud.inetutils.ignored-interfaces[0]=eth0 # 忽略eth0, 支持正则表达式
复制代码
二、手工指定IP(推荐)工具
添加如下配置:oop
#在此配置完信息后 别的服务调用此服务时使用的 ip地址就是 10.21.226.253
# 指定此实例的ip
eureka.instance.ip-address=
# 注册时使用ip而不是主机名
eureka.instance.prefer-ip-address=true
复制代码
注:此配置是配置在须要指定固定ip的服务中, 假如 A 服务我运行的服务器中有两个网卡我只有 1网卡可使用,因此就要注册服务的时候使用ip注册,这样别的服务调用A服务得时候从注册中心获取到的访问地址就是 我配置的这个参数 prefer-ip-address。源码分析