如果响应时间超过3秒,我想取消REST请求,但我还没弄清楚如何做到这一点。
所以让我说我有一个主题A:
@Override
public void run() {
RestTemplate restTemplate = new RestTemplate();
IsAliveMessage isAliveMessage = new IsAliveMessage(nodeInfo.getHostname(), nodeInfo.getPort());
IsAliveResponse isAliveResponse = restTemplate.postForObject(
"http://" + nodeInfo.getHostname() + ":" + nodeInfo.getPort() + "/node/isAlive",
isAliveMessage,
IsAliveResponse.class);
}
发出请求并希望得到B的回答:
@RequestMapping( value="/isAlive", method= RequestMethod.POST)
public IsAliveResponse isAlive() throws ConnectException {
try {
Thread.sleep(100000);
IsAliveResponse response = new IsAliveResponse("here here!" ,true);
return response;
} catch (Exception e) {
Thread.currentThread().interrupt();
}
}
B“睡觉”但没有回答,但A一直在等待答案的到来。如何在一段时间后让A放弃等待?
提前致谢
答案 0 :(得分:1)
您可以将RestTemplate配置为等待三秒钟以进行响应,如下所示:
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
private ClientHttpRequestFactory getClientHttpRequestFactory() {
int timeout = 3000;
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory =
new HttpComponentsClientHttpRequestFactory();
clientHttpRequestFactory.setConnectTimeout(timeout);
clientHttpRequestFactory.setReadTimeout(timeout);
return clientHttpRequestFactory;
}