通过使用属性文件来更改伪装客户端返回的实例(替代启动器和尤里卡自动功能区行为)

时间:2018-09-06 09:13:37

标签: spring-boot spring-cloud netflix-eureka netflix-feign netflix-ribbon

简介

因此,我们有一个用作父级的入门程序,它具有各种模板和自动配置,它们也可以加载伪装客户端。

假冒客户在下面使用eureka发现,以便遍历服务。

这是我们的一位假客户的例子:

导入org.springframework.cloud.openfeign.FeignClient;

@FeignClient(name="decide-proxy")
public interface DecideControllerApiClient extends DecideControllerApi {
}

在使用此春季启动(以及cloud starter)作为父项(在我们的pom.xml中)的项目中,我希望能够转到属性文件并执行以下操作:

eureka.client.filter.enabled=true
eureka.client.filter.services.doc-tools.host=localhost
eureka.client.filter.services.doc-tools.port=8015

我现在有办法做到这一点,但是它涉及到使用Aspects和反射,并且似乎减慢了我的项目的速度-这是一个很丑陋的技巧。

那么有没有办法通过功能区属性或其他方式做到这一点?

最好不修改入门代码?

问题是: 我们如何使用属性文件更改假客户端返回的实例。 从本质上讲,我们如何才能超越入门者和尤里卡自动功能区的行为。

当前黑客

所以我看到了以下链接:https://stackoverflow.com/a/42413801/1688441

基于此,我创建了以下似乎有效的方法:

   import com.netflix.appinfo.InstanceInfo;
    import eureka.InstanceBuildVersionProperties.InstanceHostFilter;
    import lombok.RequiredArgsConstructor;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
    import org.springframework.cloud.client.ServiceInstance;
    import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient.EurekaServiceInstance;
    import org.springframework.stereotype.Component;

    import java.lang.reflect.Field;
    import java.net.URI;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;

    @RequiredArgsConstructor
    @Aspect
    public class EurekaInstanceHostFilter {
        private final Logger logger = LoggerFactory.getLogger(this.getClass());

        private final String versionMetadataKey;
        private final InstanceBuildVersionProperties filters;

        @SuppressWarnings("unchecked")
        @Around("execution(public * org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient.getInstances(..))")
        public Object filterInstances(ProceedingJoinPoint jp) throws Throwable {
            if (filters == null || !filters.isEnabled()) logger.error("Should not be filtering...");
            List<ServiceInstance> instances = (List<ServiceInstance>) jp.proceed();

            String serviceId = (String) jp.getArgs()[0];
            InstanceHostFilter filter = filters.getServices().get(serviceId);

            if(filter != null){
                instances.forEach( instance -> {


                    try {

                        Class<?> clazz = EurekaServiceInstance.class;
                        Class<?> clazzInfo = InstanceInfo.class;

                        Field instanceField = clazz.getDeclaredField("instance");
                        instanceField.setAccessible(true);
                        InstanceInfo instanceInfo = (InstanceInfo) instanceField.get(instance);

                        String originalHostName =instanceInfo.getHostName();
                        int originalPort =instanceInfo.getPort();

                        //SET THE VALUES

                        String changeInstanceId = filter.getHost() + ":" + instance.getServiceId() + ":" +filter.getPort();
                        setField(instanceInfo, clazzInfo, "instanceId", changeInstanceId );

                        //HomePageURL
                        String newHomePageUrl = instanceInfo.getHomePageUrl().replace(originalHostName, filter.getHost())   .replace(originalPort+"", filter.getPort()+"");
                        setField(instanceInfo, clazzInfo, "homePageUrl", newHomePageUrl );

                        //StatusPageUrl
                        String statusPageUrl = instanceInfo.getStatusPageUrl().replace(originalHostName, filter.getHost())  .replace(originalPort+"", filter.getPort()+"");
                        setField(instanceInfo, clazzInfo, "statusPageUrl", statusPageUrl );

                        //healthCheckURL
                        String healthCheckUrl = instanceInfo.getHealthCheckUrl().replace(originalHostName, filter.getHost())    .replace(originalPort+"", filter.getPort()+"");
                        setField(instanceInfo, clazzInfo, "healthCheckUrl", healthCheckUrl );

                        //hostName
                        String hostName = instanceInfo.getHostName().replace(originalHostName, filter.getHost());
                        setField(instanceInfo, clazzInfo, "hostName", hostName );

                        setIntField(instanceInfo, clazzInfo, "port", filter.getPort());

                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }


                });

            }

            return instances;
        }

        private void setField(Object instanceInfo, Class<?> clazzInfo, String fieldName, String value) throws NoSuchFieldException, IllegalAccessException {
            Field instanceId = clazzInfo.getDeclaredField(fieldName);
            instanceId.setAccessible(true);
            instanceId.set(instanceInfo, value);
        }

        private void setIntField(Object instanceInfo, Class<?> clazzInfo, String fieldName, int value) throws NoSuchFieldException, IllegalAccessException {
            Field instanceId = clazzInfo.getDeclaredField(fieldName);
            instanceId.setAccessible(true);
            instanceId.setInt(instanceInfo, value);
        }

    }

    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;

    @Configuration
    @ConditionalOnProperty(name = "eureka.client.filter.enabled", havingValue = "true")
    @EnableConfigurationProperties(InstanceBuildVersionProperties.class)
    public class EurekaInstanceHostFilterAutoConfig {

        @Value("${eureka.instance.metadata.keys.version:instanceBuildVersion}")
        private String versionMetadataKey;

        @Bean
        @ConditionalOnProperty(name = "eureka.client.filter.enabled", havingValue = "true")
        public EurekaInstanceHostFilter eurekaInstanceBuildVersionFilter(InstanceBuildVersionProperties filters) {
            return new EurekaInstanceHostFilter(versionMetadataKey, filters);
        }
    }


import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.HashMap;
import java.util.Map;

import static org.apache.commons.lang3.ArrayUtils.contains;

@ConfigurationProperties("eureka.client.filter")
public class InstanceBuildVersionProperties {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * Indicates whether or not service instances versions should be filtered
     */
    @Getter @Setter
    private boolean enabled = false;

    /**
     * Map of service instance version filters.
     * The key is the service name and the value configures a filter set for services instances
     */
    @Getter
    private Map<String, InstanceHostFilter> services = new HashMap<>();

    public boolean isKept(String serviceId) {
        logger.debug("Considering service {} instance", serviceId);
        if (services.containsKey(serviceId)) {
            InstanceHostFilter filter = services.get(serviceId);
            //TODO:
            return true;
        }
        return true;
    }

    @Getter @Setter
    public static class InstanceHostFilter {
        /**
         * host to use
         */
        private String host;
        private int port;
    }
}

我注意到的上述代码使我的项目变慢了很多。 此外,由于使用了反射和方面,因此非常不方便。

其他想法

唯一的另一个想法是开始在启动器内部有条件地加载配置。因此,我可以尝试加载一个假客户端或另一个假客户端,具体取决于应用程序属性文件中的属性。

当然,这很可能意味着我们必须在每个模板,伪客户端和每个微服务的自动配置中包含调试支持。

想法?

更新

我们尝试使用属性文件和功能区属性之一再加上假名,但这没有用。像这样:

decide-proxy.ribbon.listOfServers=

1 个答案:

答案 0 :(得分:2)

bootstrap.yml中的以下配置对我有用,

ribbon:
  eureka:
    enabled: false

my-service:
  ribbon:
    listOfServers: 192.168.1.217:9010

我在zuul代理中对其进行配置,以便它可以引用未在同一eureka中注册的服务。这样,它将禁用所有的尤里卡查找。

---更新---

请参考以下链接,它可以指定一些服务以使用指定的服务器列表,而不会禁用所有eureka查找。 How to disable eureka lookup on specific @FeignClient,指定

 my-service:
    ribbon:     
      NIWSServerListClassName:com.netflix.loadbalancer.ConfigurationBasedServerList
      listOfServers: server1:18201,server2:18201

为您服务