2018-05-27 SpringCloud注册正确的IP - Eureka使用经验

在上一篇文章中提到 SpringCloud Brixton和Camden.SR7 的Inets的一点小bug
2018-05-27 开发环境下加快项目启动速度-点评CAT使用经验

问题

问题并不是很严重,注册中心当然知道客户端的IP地址 了,但是注册的时候,一般是以IP显示的。

eureka:
  instance:
      instance-id: ${spring.cloud.client.ipAddress}:${server.port}
      lease-expiration-duration-in-seconds: 30
      lease-renewal-interval-in-seconds: 10
      appname: ${spring.application.name}
      prefer-ip-address: true

就是这个spring.cloud.client.ipAddress 变量,在SpringCloud Brixton 中,SpringCloud可能会把不是无线网卡,也不是本机以太网的网卡地址注册上去。就是上一篇文章中说到的VMware的两张网卡会干扰SpringCloud的判断。这个版本的显示的和注册的地址可能都不是正确的地址。这容易导致,局域网内其他人调用的时候,不小心调用到你的机器上了,但是这个IP不通。容易出现说不清楚的网络超时问题。注册中心页面显示的IP地址也容易引起误导。

解决方案

禁用虚拟机网卡


更有意思的方案

喜欢研究技术的同学,可以看看:

虚拟机网卡继续开着,升级到SpringCloud Camden.SR7 以上

加上配置:

spring:
  cloud:
    inetutils:
      ignoredInterfaces: ['VMware.*']
      preferredNetworks: ['172.16']
      use-only-site-local-interfaces: true

这还不够:

用下面的方式打印主机地址,观察是否正确

@Component
@Slf4j
public class SelfCheckProgram implements CommandLineRunner {

    @Value("${spring.cloud.client.ipAddress}")
    private String ip;
    @Value("${spring.cloud.client.hostname}")
    private String hostName;

    @Override
    public void run(String... strings) throws Exception {
        log.warn("spring.cloud.client.ipAddress = {}" ,ip);
        log.warn("spring.cloud.client.hostname = {}", hostName);
    }
}

其实会发现打印的是正确的。但是实际上还是不太对。
再写一个随着系统启动,观察IP地址是否正确。
这里观察inetUtils的配置是否正确:

@Component
@Slf4j
public class InspectEurekaClientIp implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("inetUtilsProperties")) {
            InetUtilsProperties inetUtilsProperties = (InetUtilsProperties) bean;
            log.warn("ignored interfaces {}", inetUtilsProperties.getIgnoredInterfaces());
            log.warn("prefered network {}", inetUtilsProperties.getPreferredNetworks());
            return inetUtilsProperties;
        }

        if (beanName.equals("eurekaInstanceConfigBean")) {
            EurekaInstanceConfigBean eurekaInstanceConfigBean = (EurekaInstanceConfigBean) bean;
            log.warn("eurekaInstanceConfig Ip: {}", eurekaInstanceConfigBean.getIpAddress());
            log.warn("eurekaInstanceConfig IstanceId: {}", eurekaInstanceConfigBean.getInstanceId());
            return bean;
        }

        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}

inetsUtilsProperties会打印多次:
其实第一次的配置还是不正确,没有注入忽略的网卡配置,但是后面打印得却是正确的。。==

阅读源码其实可以发现:

public class HostInfoEnvironmentPostProcessor
        implements EnvironmentPostProcessor, Ordered {

    // Before ConfigFileApplicationListener
    private int order = ConfigFileApplicationListener.DEFAULT_ORDER - 1;

    @Override
    public int getOrder() {
        return this.order;
    }

.......省略部分方法

    private HostInfo getFirstNonLoopbackHostInfo(ConfigurableEnvironment environment) {
        InetUtilsProperties target = new InetUtilsProperties();
        RelaxedDataBinder binder = new RelaxedDataBinder(target,
                InetUtilsProperties.PREFIX);
        binder.bind(new PropertySourcesPropertyValues(environment.getPropertySources()));
        try (InetUtils utils = new InetUtils(target)) {
            return utils.findFirstNonLoopbackHostInfo();
        }
    }
}

SpringCloud新增了binder.bind,逻辑,然而不幸的是,这个PropertySourcesPropertyValues 拿不到配置文件的配置。只能通过系统环境变量。猜测可能是启动得比较早,还没来得及读取application.yml生成PropertySource。

最终解决方案

把上面的类升级成EnvironmnetPostProcessor

META-INF下面新增spring.factories
写入

org.springframework.boot.env.EnvironmentPostProcessor=\
com.github.slankka.config.InspectEurekaClientIp

InspectEurekaClientIp 多实现一个接口:

@Component
@Slf4j
public class InspectEurekaClientIp implements BeanPostProcessor, EnvironmentPostProcessor, Ordered {

    @Override
    public int getOrder() {
//这里是依据HostInfoEnvironmentPostProcessor 的优先级,这里让本类优先处理。
        return ConfigFileApplicationListener.DEFAULT_ORDER - 2;
    }

    /**
     * 鉴于 HostInfoEnvironmentPostProcessor 处理inetUtilsProperties 时,
     * 只从系统环境变量中取得空的  ignoredInterfaces.
     * 这里强制写入,防止被传入了错误的VMware的网卡的IP地址
     */
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        Map<String, Object>  ignoredInterfaces = Maps.newHashMap();
        ignoredInterfaces.put("spring.cloud.inetutils.ignoredInterfaces", Lists.newArrayList("VMware.*"));
        SystemEnvironmentPropertySource systemEnvironmentPropertySource = new SystemEnvironmentPropertySource("systemEnvironment", ignoredInterfaces);
        environment.getPropertySources().addLast(systemEnvironmentPropertySource);
    }
}

//其余内容和上面的相同,此处省略

其实还有更简单的方案

相比上面的方案而言,每一个人都需要自己配置,那就是在环境变量里面添加,想想就觉得很丑,这么长,容易忘加。但确保至少是Spring-cloud Camden.SR7版本或以上

总结

Spring框架之所以这么受欢迎,就是因为他的容器管理,IOC,等等技术,使得应用可以方便的做任何自定义修改,而且Spring是尽量避免硬编码的启动某个东西,追求注解自动化。
十分优秀。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容