如何使用RestTemplate调用多个主机

问题描述 投票:1回答:1

考虑两个主机host1 =“” http://localhost:8080/springrestexample/employee/id“和host2 =” http:// localhost:8081 / springrestexample / student / id“。我想使用单个RestTemplate调用这些主机。首先,我要呼叫host1,然后如果返回与服务不可用相关的任何错误代码,则我要呼叫host2。谢谢。

private static void getDetails()
{
    final String host1 = "http://localhost:8080/springrestexample/employee/id";

    final String host2 = "http://localhost:8080/springrestexample/student/id";


    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject(host1, String.class);

    System.out.println(result);
}

spring-boot resttemplate
1个回答
1
投票

Resttemplate发生某些错误时会引发异常。

最简单的方法可能是::

try {
   restTemplate.getForObject(host1, String.class);
} catch (HttpClientErrorException | HttpServerErrorException e) {
   restTemplate.getForObject(host2, String.class);
   ...
}
© www.soinside.com 2019 - 2024. All rights reserved.