java.net.UnknownHostException 在 Eureka 服务发现期间

java.net.UnknownHostException during Eureka service discovery

根据这篇博文 https://spring.io/blog/2015/07/14/microservices-with-spring

能够运行应用程序没有任何问题。按此顺序:

但是当尝试通过 Web 应用程序访问任何服务时(http://localhost:3333/) which uses the http://ACCOUNTS-SERVICE url to access any accounts service endpoints like http://ACCOUNTS-SERVICE/accounts/123456789 我收到错误响应:

Response Status: 500 (Internal Server Error)
Cause: org.springframework.web.client.ResourceAccessException I/O error on GET request for "http://ACCOUNTS-SERVICE/accounts/123456789": ACCOUNTS-SERVICE; nested exception is java.net.UnknownHostException: ACCOUNTS-SERVICE

当我提供真实地址时(http://localhost:2223/) of the accounts service to the web server instead of the http://ACCOUNTS-SERVICE一切正常,但在这种情况下没有服务发现。

源代码保存在:https://github.com/paulc4/microservices-demo

此问题是由于 RestTemplate 不再在 Brixton 发布火车 (Spring Cloud 1.1.0.RELEASE) 中自动创建,因此 RestTemplate 无法正确解析 http://ACCOUNTS-SERVICE url 使用服务发现服务器。

在使用 @LoadBalanced 声明 RestTemplate bean 后能够解决此问题,如下所示:

@Bean
@LoadBalanced
public RestTemplate restTemplate() {
    return new RestTemplate();
}