Nacos中注册IP的选择
在启动微服务的时候因为电脑中的网卡(虚拟网卡VPN等等)太多导致注册nacos中注册的IP地址是错误的:可以使用如下配置注册你想注册的网卡spring:cloud:inetutils:preferredNetworks:- 10.10
·
在启动微服务的时候因为电脑中的网卡(虚拟网卡VPN等等)太多导致注册nacos中注册的IP地址是错误的:
可以使用如下配置注册你想注册的网卡
spring:
cloud:
inetutils:
preferredNetworks:
- 10.10 #这里可以是IP的全拼也可以是一部分.主要是用IP去匹配的
一下为关键代码: org.springframework.cloud.commons.util.InetUtils中的
public InetAddress findFirstNonLoopbackAddress() {
InetAddress result = null;
try {
int lowest = 2147483647;
Enumeration nics = NetworkInterface.getNetworkInterfaces();
label61:
while(true) {
NetworkInterface ifc;
do {
while(true) {
do {
if (!nics.hasMoreElements()) {
break label61;
}
ifc = (NetworkInterface)nics.nextElement();
} while(!ifc.isUp());
this.log.trace("Testing interface: " + ifc.getDisplayName());
if (ifc.getIndex() >= lowest && result != null) {
if (result != null) {
continue;
}
break;
}
lowest = ifc.getIndex();
break;
}
} while(this.ignoreInterface(ifc.getDisplayName()));
Enumeration addrs = ifc.getInetAddresses();
while(addrs.hasMoreElements()) {
InetAddress address = (InetAddress)addrs.nextElement();
//重点是isPreferredAddress代码
if (address instanceof Inet4Address && !address.isLoopbackAddress() && this.isPreferredAddress(address)) {
this.log.trace("Found non-loopback interface: " + ifc.getDisplayName());
result = address;
}
}
}
} catch (IOException var8) {
this.log.error("Cannot get first non-loopback address", var8);
}
if (result != null) {
return result;
} else {
try {
return InetAddress.getLocalHost();
} catch (UnknownHostException var7) {
this.log.warn("Unable to retrieve localhost");
return null;
}
}
}
//主要在这里看到有个配置属性控制的 preferredNetworks
boolean isPreferredAddress(InetAddress address) {
if (this.properties.isUseOnlySiteLocalInterfaces()) {
boolean siteLocalAddress = address.isSiteLocalAddress();
if (!siteLocalAddress) {
this.log.trace("Ignoring address: " + address.getHostAddress());
}
return siteLocalAddress;
} else {
List<String> preferredNetworks = this.properties.getPreferredNetworks();
if (preferredNetworks.isEmpty()) {
return true;
} else {
Iterator var3 = preferredNetworks.iterator();
String regex;
String hostAddress;
do {
if (!var3.hasNext()) {
this.log.trace("Ignoring address: " + address.getHostAddress());
return false;
}
regex = (String)var3.next();
hostAddress = address.getHostAddress();
} while(!hostAddress.matches(regex) && !hostAddress.startsWith(regex));
return true;
}
}
}
// 配置文件定义如下:
@ConfigurationProperties("spring.cloud.inetutils")
public class InetUtilsProperties {
public static final String PREFIX = "spring.cloud.inetutils";
private String defaultHostname = "localhost";
private String defaultIpAddress = "127.0.0.1";
@Value("${spring.util.timeout.sec:${SPRING_UTIL_TIMEOUT_SEC:1}}")
private int timeoutSeconds = 1;
private List<String> ignoredInterfaces = new ArrayList();
private boolean useOnlySiteLocalInterfaces = false;
private List<String> preferredNetworks = new ArrayList();
....
更多推荐
已为社区贡献1条内容
所有评论(0)