Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Microservices - RestTemplate UnknownHostException

I have a simple setup with a Eureka service registration server, a service for the public API and a service that gets called from the public API using RestTemplate. Eureka tells me that the services are successfully registered, but when I call the service

@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);
    }
}

I get the following exception

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

I created a sample project to illustrate my setup, maybe someone could take a look at it and tell me what's wrong with my setup.

https://github.com/KenavR/spring-boot-microservices-example

thanks

like image 226
KenavR Avatar asked Jan 07 '23 02:01

KenavR


1 Answers

As suggested by patrick-grimard switching to Brixton and changing the code were needed fixed the issues. Working Solution is on Github.

Also changed the posted id from request param to request body, which also changed the way I add it to the request.

Service endpoint

@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 creation

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

Calling service

@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);
    }
}
like image 150
KenavR Avatar answered Jan 08 '23 16:01

KenavR