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