我有一个 Eureka 服务注册服务器、一个公共(public) API 服务和一个使用 RestTemplate 从公共(public) 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
谢谢
最佳答案
正如 patrick-grimard 建议的那样,切换到 Brixton 并更改代码需要解决这些问题。工作解决方案在 Github 上。
还将发布的 id
从请求参数更改为请求正文,这也改变了我将其添加到请求中的方式。
服务端点
@RequestMapping(method = RequestMethod.POST, produces = "application/json; charset=utf-8")
public @ResponseBody Map<String, String> getTest(@RequestBody Map<String, Long> params) {
Map<String, String> response = new HashMap<>();
response.put("name", "My Service");
return response;
}
RestTemplate 创建
@Configuration
public class PublicAPIConfiguration {
@LoadBalanced
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
}
调用服务
@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, Long> vars = new HashMap<>();
vars.put("id", 1L);
return restTemplate.postForObject(serviceUrl+"/test", vars, Map.class);
}
}
关于java - 微服务 - RestTemplate UnknownHostException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37159662/