一尘不染

微服务-RestTemplate UnknownHostException

spring-boot

我使用Eureka服务注册服务器进行了简单的设置,使用了公共API的服务以及使用RestTemplate从公共API调用的服务。尤里卡告诉我服务已成功注册,但是当我致电服务时

@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

谢谢


阅读 708

收藏
2020-05-30

共1个答案

一尘不染

正如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);
    }
}
2020-05-30