Java 指定时间内如果请求没有返回值就重试怎么实现(异步)

2023-03-29 19:13:31 +08:00
 EddieWang

1.有个 spring retry 的重试,但是这个似乎没有办法实现超时之后重试 2.我们使用的是 org.springframework.web.reactive.function.client.WebClient ,我知道有个 retryWhen 的东西,但是由于封装了 sdk 所以我不好改它 所以大佬们有什么其它好的实现呢!!!!!

1585 次点击
所在节点    程序员
10 条回复
EddieWang
2023-03-29 19:15:56 +08:00
也有使用 Mono.defer 似乎好像也不太行?
dqzcwxb
2023-03-29 19:26:22 +08:00
completablefuture timedGet()可以设置超时时间,超时后会抛出 TimeoutException 异常你捕获该异常进行重试就可以了
kwh
2023-03-29 20:17:58 +08:00
resilience4j ???
hn16838220
2023-03-29 21:26:46 +08:00
我记得 guava 的 retry 是可以写条件判断是否重试的
why1001
2023-03-29 22:41:36 +08:00
可以看看 project reactor 文档,webflux 也是在这上边实现的,里边有个 timeout()还有其它的可以实现。
Helsing
2023-03-29 22:45:33 +08:00
用 reactor 、rxjava 这些框架比较好实现
shinyruo2020
2023-03-29 22:51:56 +08:00
for 循环 + countDownLatch.await 指定超时时间
bthulu
2023-03-30 10:32:31 +08:00
You can retry requests using the Java 11 HTTP client by composing the returned future with re-schedules in a loop. Here’s an example:

public static <T> CompletableFuture<T> retry(Supplier<CompletableFuture<T>> action, int maxRetries) {
return action.get().handle((result, throwable) -> {
if (throwable != null && maxRetries > 0) {
return retry(action, maxRetries - 1);
} else if (throwable != null) {
throw new RuntimeException(throwable);
} else {
return result;
}
}).thenCompose(Function.identity());
}
This method takes a Supplier that returns a CompletableFuture, and an integer maxRetries that specifies the maximum number of retries. It returns a new CompletableFuture that retries the action if it fails with an exception.

Here’s how you can use this method to retry an HTTP request:

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com"))
.build();

CompletableFuture<HttpResponse<String>> response = retry(() -> client.sendAsync(request, HttpResponse.BodyHandlers.ofString()), 3);
This code retries the HTTP request up to three times if it fails with an exception.

I hope this helps! Let me know if you have any other questions.
yazinnnn
2023-03-30 10:33:34 +08:00
Mono.defer(() -> {
System.out.println(LocalDateTime.now());
val integer = Random.Default.nextInt(100);
System.out.println(integer);
if (integer > 80) {
return Mono.just(100);
} else {
return Mono.never();
}
})
.timeout(Duration.ofSeconds(1))
.retry(10)

defer 就行
liuhuan475
2023-03-30 10:41:58 +08:00
楼上的回答都有同样的问题,就是应用挂掉重试就不会进行了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/928256

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX