gpt4 book ai didi

java - 使用 SpringFlux 的 webclient 重复 Mono

转载 作者:行者123 更新时间:2023-12-01 17:21:44 28 4
gpt4 key购买 nike

情况如下:我发送了第一个请求,然后我以5秒的间隔重复发送了第二个请求。如果第二个请求收到成功响应,我会将其保存在数据库中并执行一些操作,如果它收到不成功(完整)响应,则应重复请求。当尝试次数大于 3 时,我需要停止重复第二个请求。我该如何做到这一点?

     return firstRequestSenderService.send(request)
.flatMap(resp -> {
AtomicInteger attempts = new AtomicInteger(0);
String url = normalizeUrl(resp.getResult());
return Mono.defer(() -> {
log.info("Second request, attempt = {}, params = {}", attempts.get(), param);
return secondRequestSenderService.send(param, url, attempts.getAndIncrement());
})
.filter(this::isCompleteResponse)
// i try .filter(b -> attempts.get() > 2)
.doOnNext(r -> log.info("Save report"))
.map(secondResp -> dataSaver.saveReport(param, secondResp))
.doOnNext(r -> log.info("Send request to another service"))
.flatMap(r -> secondRequestSender.sendPdf(r)))
.doOnNext(bytes -> dataSaver.saveAnotherReport(param, bytes))
.repeatWhenEmpty(req -> Flux.interval(Duration.ofSeconds(5)));
// also try .repeatWhenEmpty(3, req -> Flux.interval(Duration.ofSeconds(5)));
})
.then(Mono.empty());

最佳答案

检查reactor-addons你可以做类似的事情

    return firstRequestSenderService.send(request)
.flatMap(resp -> {
return secondRequestSenderService
.send(param, url, attempts.getAndIncrement())
.retryWhen(Retry.any()
.randomBackoff(Duration.ofMillis(100), Duration.ofMillis(5000))
.retryMax(3));

});

你也可以使用reactor core retry utils RetryBackoffSpec来做到这一点当你使用最新的 spring webflux 时你会得到这一点

  RetryBackoffSpec retryBackoffSpec = Retry
.fixedDelay(3, Duration.ofSeconds(5));
return firstRequestSenderService.send(request)
.flatMap(resp -> {
return secondRequestSenderService
.send(param, url, attempts.getAndIncrement())
.retryWhen(retryBackoffSpec);
});

关于java - 使用 SpringFlux 的 webclient 重复 Mono,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61279841/

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