我有一个简单的设置,包括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,它应该会自动注入负载均衡的 RestTemplate。我唯一能想到的建议是给您的RestTemplate
加上@LoadBalanced
注解,看看是否有所不同。 - Patrick Grimard@LoadBalanced @Bean RestTemplate
,因为Brixton不再默认创建一个。然后,你可以像往常一样进行@Autowire
。除此之外,你也可以尝试使用小写的服务ID来调用你的服务,如http://my-service/test
。 - Patrick Grimard