一、問題場景
服務器上分別配置了eth0, eth1和eth2三塊網卡,只有eth1的地址可供其它機器訪問,eth0和eth2的 IP 無效。在這種情況下,服務注冊時Eureka Client會自動選擇eth0作為服務ip, 導致其它服務無法調用。
二、問題原因
由於官方並沒有寫明Eureka Client探測本機IP的邏輯,所以只能翻閱源代碼。Eureka Client的源碼在eureka-client模塊下,com.netflix.appinfo包下的InstanceInfo類封裝了本機信息,其中就包括了IP地址。在 Spring Cloud 環境下,Eureka Client並沒有自己實現探測本機IP的邏輯,而是交給Spring的InetUtils工具類的findFirstNonLoopbackAddress()方法完成的:
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; }
通過源碼可以看出,該工具類會獲取所有網卡,依次進行遍歷,取ip地址合理、索引值最小且不在忽略列表的網卡的ip地址作為結果。如果仍然沒有找到合適的IP, 那么就將InetAddress.getLocalHost()做為最后的fallback方案。
三、解決方案
A.忽略指定網卡
通過上面源碼分析可以得知,spring cloud肯定能配置一個網卡忽略列表。通過查文檔資料得知確實存在該屬性:
spring.cloud.inetutils.ignored-interfaces[0]=eth0 # 忽略eth0, 支持正則表達式
因此,第一種方案就是通過配置application.properties
讓應用忽略無效的網卡。
B.配置host
當網查遍歷邏輯都沒有找到合適ip時會走JDK的InetAddress.getLocalHost()。該方法會返回當前主機的hostname, 然后會根據hostname解析出對應的ip。因此第二種方案就是配置本機的hostname和/etc/hosts文件,直接將本機的主機名映射到有效IP地址。
C.手工指定IP(推薦)
# 指定此實例的ip eureka.instance.ip-address= # 注冊時使用ip而不是主機名 eureka.instance.prefer-ip-address=true
參見:http://blog.csdn.net/neosmith/article/details/53126924
D.啟動時指定IP
java -jar -Dspring.cloud.inetutils.preferred-networks=192.168.20.123