spring cloud 网卡选择 Myth丶恋晨 2022-01-12 07:07 191阅读 0赞 spring-cloud-commons项目为Spring Cloud生态提供了顶层的抽象和基础设施的实现。 网络这个最基本的基础设施也是在这里有对应的实现:InetUtils、InetUtilsProperties和UtilAutoConfiguration提供了网络配置相关的功能。 [相关配置的spring cloud官方文档][spring cloud] springcloud 中选择网卡的源码(可以从 HostInfoEnvironmentPostProcessor 切入): 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(); } catch (UnknownHostException e) { log.warn("Unable to retrieve localhost"); } return null; } 所以spring cloud默认是会采用绑定了ip的最后一块网卡,如果与实际需求不对等的话,则需要通过配置进行手动选择,无论是手动忽略某个网卡还是手动指定ip。 配置可以覆盖自动选择的源码: public class HostInfoEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { // Before ConfigFileApplicationListener private int order = ConfigFileApplicationListener.DEFAULT_ORDER - 1; @Override public int getOrder() { return this.order; } @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { InetUtils.HostInfo hostInfo = getFirstNonLoopbackHostInfo(environment); LinkedHashMap<String, Object> map = new LinkedHashMap<>(); map.put("spring.cloud.client.hostname", hostInfo.getHostname()); map.put("spring.cloud.client.ip-address", hostInfo.getIpAddress()); MapPropertySource propertySource = new MapPropertySource( "springCloudClientHostInfo", map); environment.getPropertySources().addLast(propertySource); } private HostInfo getFirstNonLoopbackHostInfo(ConfigurableEnvironment environment) { InetUtilsProperties target = new InetUtilsProperties(); ConfigurationPropertySources.attach(environment); Binder.get(environment).bind(InetUtilsProperties.PREFIX, Bindable.ofInstance(target)); try (InetUtils utils = new InetUtils(target)) { return utils.findFirstNonLoopbackHostInfo(); } } } [spring cloud]: https://cloud.spring.io/spring-cloud-static/spring-cloud.html#ignore-network-interfaces
还没有评论,来说两句吧...