gpt4 book ai didi

java - 如果响应时间过长,则取消休息请求

转载 作者:行者123 更新时间:2023-11-30 02:42:01 24 4
gpt4 key购买 nike

如果响应时间超过 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在一定时间后放弃等待?

提前致谢

最佳答案

您可以将 RestTemplate 配置为等待三秒以获得响应,如下所示:

RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

private ClientHttpRequestFactory getClientHttpRequestFactory() {
int timeout = 3000;
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory =
new HttpComponentsClientHttpRequestFactory();
clientHttpRequestFactory.setConnectTimeout(timeout);
clientHttpRequestFactory.setReadTimeout(timeout);
return clientHttpRequestFactory;
}

关于java - 如果响应时间过长,则取消休息请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41379506/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com