如何重试Spring WebClient根据响应重试操作? [英] how to retry Spring WebClient to retry the operation based on the response?
问题描述
我一直在学习spring webflux,并被困在其中.
I've been learning spring webflux and got stuck into this one.
我已经使用WebClient从Spring应用程序请求了REST API.我想根据响应重试该请求.可以说,如果响应的属性为status: 'not-ready'
,那么我需要一秒钟后重试相同的操作.
I've made a request to REST API from Spring app using WebClient. I want to retry the request based on the response. lets say if the response has property status: 'not-ready'
, then I need to retry the same operation after a second.
我尝试了以下方法,但不确定如何实现
I tried the following way, but not sure how to implement it
public Flux<Data> makeHttpRequest(int page) {
Flux<Data> data = webClient.get()
.uri("/api/users?page=" + page)
.retrieve()
.bodyToFlux(Data.class);
return data;
}
GET : /api/users returns the folowing response
ex: 1 {
status: 'ready',
data: [......]
}
ex: 2 {
status: 'not-ready',
data: null
}
任何帮助将不胜感激.
Any help would be appreciated.
推荐答案
我认为实现所需的重试逻辑相当容易. 类似于以下内容:
I think it is fairly easy to implement the desired retry logic. Something along the lines of:
public class SampleRequester {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private WebClient client;
public SampleRequester() {
this.client = WebClient.create();
}
public void scheduleRequest(int secondsDelay) {
scheduler.schedule(this::initiateRequest, secondsDelay, SECONDS);
}
private void initiateRequest() {
Mono<ResponseData> response = client.get()
.uri("example.com")
.retrieve()
.bodyToMono(ResponseData.class);
response.subscribe(this::handleResponse);
}
private void handleResponse(ResponseData body) {
if("ready".equals(body.getStatus())) {
System.out.println("No Retry");
// Do something with the data
} else {
System.out.println("Retry after 1 second");
scheduleRequest(1);
}
}
}
我使用以下简单模型进行响应:
I used the following simple model for the response:
public class ResponseData implements Serializable {
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
然后,您将调用SampleRequester.scheduleRequest(0)立即发起第一个调用. 当然,您还需要进行调整,以避免硬编码请求url,扩展ResponseData,使延迟可配置和/或指数回退等.
Then you would call SampleRequester.scheduleRequest(0) to initiate the first call immediately. Of course you would also need to adapt to avoid hard-coding the request url, extending the ResponseData, make the delay configurable and/or exponential backoff etc.
这篇关于如何重试Spring WebClient根据响应重试操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!