如何使用 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);
...
}

最新更新