如何使用 RestTemplate 调用多个主机

How to call multiple hosts using RestTemplate

考虑两个主机 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);
}

Resttemplate 在发生错误时抛出异常。

最简单的方法可能是::

try {
   restTemplate.getForObject(host1, String.class);
} catch (HttpClientErrorException | HttpServerErrorException e) {
   restTemplate.getForObject(host2, String.class);
   ...
}