简体   繁体   English

如何重试 Spring WebClient 根据响应重试操作?

[英]how to retry Spring WebClient to retry the operation based on the response?

I've been learning spring webflux and got stuck into this one.我一直在学习 spring webflux 并陷入了这个困境。

I've made a request to REST API from Spring app using WebClient.我已经使用 WebClient 从 Spring 应用程序向 REST API 发出请求。 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.假设响应具有属性status: 'not-ready' ,那么我需要在一秒钟后重试相同的操作。

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:我使用以下简单的 model 作为响应:

public class ResponseData implements Serializable {

    private String status;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}   

Then you would call SampleRequester.scheduleRequest(0) to initiate the first call immediately.然后您将调用 SampleRequester.scheduleRequest(0) 以立即启动第一个调用。 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.当然,您还需要适应避免硬编码请求 url、扩展 ResponseData、使延迟可配置和/或指数退避等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM