gpt4 book ai didi

java - Jodah 故障安全库超时时间比预期要长

转载 作者:行者123 更新时间:2023-12-01 16:19:07 29 4
gpt4 key购买 nike

我有一种情况,我想实现 API 重试机制。假设我有一个调用第三方 API 的 API,其中正常响应时间低于 2 秒,但有时我们会收到错误消息,提示“服务不可用”、“网关超时”等。

所以我上网看看我们是否有一个库来处理这些事情,我发现https://jodah.net/failsafe/

<小时/>

使用库的目的:-

如果在 5 秒内没有得到结果,我将取消当前调用的执行并再试一次。

为此,在库中我可以看到我们有超时重试策略

首先我尝试超时。

 Timeout<Object> timeout = Timeout.of(Duration.ofMillis(1000)).withCancel(true)
.onFailure(e -> logger.error("Connection attempt timed out {} {} ",new DateTime(), e.getFailure()))
.onSuccess(e -> logger.info("Execution completed on time"));


try {
logger.info("TIme: {}", new DateTime());
result = Failsafe.with(timeout).get(() -> restTemplate.postForEntity(messageSendServiceUrl, request, String.class));

} catch (TimeoutExceededException | HttpClientErrorException e) {
logger.info("TIme: {}", new DateTime());
logger.error("Timeout exception", e);

} catch (Exception e) {
logger.error("Exception", e);
}

但是在计算时间时,我在调用 API 和接收 TimeoutExceededException 之间有 20 秒的延迟,这应该是 1 秒,因为持续时间是 Duration.ofMillis(1000) 。下面您可以看到 21 秒的差异。

TIme: 2020-06-11T10:00:17.964+05:30
Connection attempt timed out 2020-06-11T10:00:39.037+05:30 {}

你能告诉我我在这里做错了什么吗?

其次是重试策略

RetryPolicy<Object> retryPolicy = new RetryPolicy<>()
.handle(HttpClientErrorException.class, TimeoutExceededException.class, Exception.class)
.withDelay(Duration.ofSeconds(1))
.withMaxRetries(3);

我希望在 3 秒后发生一次 TimeoutExceededException 异常,延迟 1 秒,再次触发请求,最多重试 3 次。我用它作为

 result = Failsafe.with(retryPolicy,timeout).get(() -> restTemplate.postForEntity(messageSendServiceUrl, request, String.class));

最佳答案

get 是一个阻塞或同步操作,它使用调用线程。故障安全几乎没有办法提前停止。超时最好与异步操作结合使用,通常由 *Async 方法指示。请务必阅读https://jodah.net/failsafe/schedulers/因为默认值有一些影响,并且对于 IO 密集型操作来说通常是一个糟糕的选择。

关于java - Jodah 故障安全库超时时间比预期要长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62317279/

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