【发布时间】:2016-09-06 16:18:04
【问题描述】:
我有一个简单的设置,其中包含一个 Eureka 服务注册服务器、一个公共 API 服务和一个使用 RestTemplate 从公共 API 调用的服务。 Eureka告诉我服务注册成功了,但是当我调用服务时
@Service
public class MyServiceService {
@Autowired
private RestTemplate restTemplate;
private final String serviceUrl;
public MyServiceService() {
this.serviceUrl = "http://MY-SERVICE";
}
public Map<String, String> getTest() {
Map<String, String> vars = new HashMap<>();
vars.put("id", "1");
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
return restTemplate.postForObject(serviceUrl+"/test", "", Map.class, vars);
}
}
我得到以下异常
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed;
nested exception is org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://MY-SERVICE/test": MY-SERVICE;
nested exception is java.net.UnknownHostException: MY-SERVICE] with root cause java.net.UnknownHostException: MY-SERVICE
我创建了一个示例项目来说明我的设置,也许有人可以看看它并告诉我我的设置有什么问题。
https://github.com/KenavR/spring-boot-microservices-example
谢谢
【问题讨论】:
-
看起来好像注入的
RestTemplate不是负载平衡的。由于您在项目中使用 Spring Cloud Angel.SR6,它应该自动注入负载均衡的。我能想到的唯一建议是用@LoadBalanced注释您的RestTemplate,看看这是否会有所不同。 -
我过去和现在都试过了,遗憾的是错误保持不变。
-
你试过Spring Cloud Brixton.RELEASE吗,今天发布了。请注意,使用 Brixton,您必须定义自己的
@LoadBalanced @Bean RestTemplate,因为默认情况下 Brixton 不再创建一个。然后你可以像往常一样@Autowire它。除此之外,您可以尝试使用小写http://my-service/test的服务 ID 调用您的服务。 -
切换到 Brixton 并更改代码需要解决问题,谢谢
标签: java spring-boot spring-cloud microservices netflix-eureka