4

我正在尝试从我的一个微服务中访问外部服务。我使用 Spring Cloud、Eureka 作为注册表和 Spring boot 作为主要框架。

Map<String, String> urlVariables = new HashMap<>();
    urlVariables.put("ip_address", IP);
    urlVariables.put("port", PORT);

    ResponseObject state =
            restTemplate.getForObject("http://{ip_address}:{port}/state/", ResponseObject.class, urlVariables);

据我所见,Spring Cloud 将 Ribbon 作为 Rest Template 的 HTTP 客户端注入,当我尝试访问此 IP(例如:)时193.172.x.x,会产生以下错误:

java.lang.IllegalStateException:在 org.springframework.cloud.netflix.ribbon.RibbonClientHttpRequestFactory.createRequest(RibbonClientHttpRequestFactory.java:64) 在 org.springframework.http.client.support.HttpAccessor.createRequest(HttpAccessor 中没有可用于 193.172.xx 的实例.java:76) 在 org.springframework.web.client.RestTemplate.execute(RestTemplate.java:540) 在 org.springframework.web 的 org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:567)。 client.RestTemplate.getForObject(RestTemplate.java:247)

看起来 Ribbon 正在尝试查找具有该名称的微服务实例,而不是向外查找。有什么方法可以配置 Ribbon 以查找外部 IP,还是仅供内部使用?

4

2 回答 2

5

您正在注入 RestTemplate 的 @LoadBalanced 版本。你必须确保你的 RestTemplate 是普通的。您可以使用new RestTemplate(). 如果它是一个 bean,只需添加一个限定符以确保您注入正确版本的RestTemplate.

于 2016-03-07T09:51:40.940 回答
1

您可以尝试的是在代码中使用服务 ID 并配置真实实例:

ResponseObject state =
            restTemplate.getForObject("http://myExternalService/state/", ResponseObject.class, urlVariables);

比你为你的服务配置一个静态的端点列表

myExternalService.ribbon.listOfServers=http://ip:port

这样,您就不会为此服务使用服务发现。

http://projects.spring.io/spring-cloud/docs/1.0.3/spring-cloud.html#spring-cloud-ribbon-without-eureka

于 2016-03-07T09:46:34.443 回答