如何延迟重复的 WebClient 获取请求 [英] How to delay repeated WebClient get request

查看:83
本文介绍了如何延迟重复的 WebClient 获取请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Spring 5 WebClient 从 REST api 重复获取正在运行的进程的某些状态.

I am using the Spring 5 WebClient to repeatedly fetch some state of a running process from a REST api.

这里的帮助下 我现在想到了这个解决方案:

With help from here I for now came to this solution:

webClient.get().uri(...).retrieve.bodyToMono(State.class)
          .repeat()
          .skipUntil(state -> stateFinished())
          .limitRequest(1)
          .subscribe(state -> {...});

虽然这有效,但 get 请求以非常高的速率被触发.将请求速率限制为每秒 1 个请求的正确方法是什么?

While this works, the get request is fired at a very high rate. What would be the right way to limit the request rate to let's say 1 request per second?

我尝试使用 delayElements(Duration.ofSeconds(1)) 但这只会延迟结果,而不是请求本身.

I tried using delayElements(Duration.ofSeconds(1)) but that only delays the results, not the request itself.

推荐答案

您可以将 repeatWhen 运算符与配套的 Publisher

You could use repeatWhen operator with your custom implementation of the companion Publisher

Mono.just("test")
        .repeatWhen(longFlux -> Flux.interval(Duration.ofSeconds(1)))
        .take(5)
        .log()
        .blockLast();

或使用 reactor-addons 中的 Repeate 功能>

Mono.just("test")
        .repeatWhen(Repeat.times(Long.MAX_VALUE)
                .fixedBackoff(Duration.ofSeconds(1)))
        .take(5)
        .log()
        .blockLast();

这篇关于如何延迟重复的 WebClient 获取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆