AsyncRestTemplate的工具使用DiscoveryClient解析主机名

时间:2018-04-11 07:41:35

标签: java spring-cloud

虽然spring-cloud-commons项目提供了一种方便的方法来检测来自服务发现的服务名称解析RestTemplate(通过使用@LoadBalanced注释进行标记)。同样的方式对AsyncRestTemplate无效。

为了解决这个问题,我必须编写自己的代码,该代码特定于用于HTTP通信的异步框架的底层实现。就我而言,它是Apache HttpComponents项目。

public class ServiceDiscoveryAwareRoutePlanner implements HttpRoutePlanner {

    private final static Logger LOGGER = LoggerFactory.getLogger(ServiceDiscoveryAwareRoutePlanner.class);

    private final DiscoveryClient discoveryClient;

    public ServiceDiscoveryAwareRoutePlanner(DiscoveryClient discoveryClient) {
        this.discoveryClient = Objects.requireNonNull(discoveryClient, "discoveryClient");
    }

    @Override
    public HttpRoute determineRoute(HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext) throws HttpException {

        List<ServiceInstance> serviceInstances = discoveryClient.getInstances(httpHost.getHostName());
        if ( !serviceInstances.isEmpty() ){
            Random rnd = new Random();
            int serviceInstanceCount = serviceInstances.size();
            ServiceInstance si = serviceInstances.get(rnd.nextInt(serviceInstanceCount));
            LOGGER.debug("Replacing hostname: {} to address from service discovery: {}", httpHost.getHostName(), si.getUri());
            return new HttpRoute(new HttpHost(si.getHost(), si.getPort(), si.isSecure() ? "https" : "http"));
        } else {
            return new HttpRoute(httpHost);
        }
    }
}

任何支持与RestTemplate&amp; @LoadBalanced的{​​{1}}注释?

0 个答案:

没有答案