【问题标题】:Short polling using WebFlux使用 WebFlux 进行短轮询
【发布时间】:2021-06-03 22:56:41
【问题描述】:

我有这个发帖方式:

webClientBuilder
                .build()
                .get()
                .uri("uri")
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .onStatus(HttpStatus::isError, response -> Mono.error(new CustomException("Response is in status: ".concat(response.statusCode().toString()))))
                .bodyToMono(GetResponse.class)
                .log()
                .flatMap(response ->
                        Mono.fromSupplier(() -> updateMember(entity.getId(), getScore(response)))
                                .subscribeOn(Schedulers.boundedElastic()))
                .block();

我应该对其创建一个简短的投票,因为我调用的 api 可能会延迟回答我,我应该能够调用它几次,也许每 3/5 秒一次。外部服务总是给我一个答案,但我必须验证答案中的特定字段不为空。我最多必须重复5次,如果5次后返回null,我会将null传递给我的方法(updateMember)。

我正在尝试这样的事情:

webClientBuilder
                .build()
                .get()
                .uri("uri")
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .onStatus(HttpStatus::isError, response -> Mono.error(new CustomException("response is in status: ".concat(response.statusCode().toString()))))
                .bodyToMono(GetResponse.class)
                .filter(response -> Objects.nonNull(response.getAnag().getSummary()))
                .repeatWhenEmpty(Repeat.onlyIf(repeatContext -> true)
                        .exponentialBackoff(Duration.ofSeconds(5), Duration.ofSeconds(10)).timeout(Duration.ofSeconds(30)))
                .delaySubscription(Duration.ofSeconds(10))
                .flatMap(response -> Mono.fromSupplier(() -> updateMember(entity.getId(), response.getAnag().getSummary()))
                        .subscribeOn(Schedulers.boundedElastic()))
                .block();

我想最多重复 5 次,前提是答案中的值为 null,否则我直接传递该值。

你能帮帮我吗?

【问题讨论】:

    标签: java spring-boot spring-webflux polling spring-webclient


    【解决方案1】:

    如果由于延迟而导致超时异常,您可以将 '.retry() 的运算符之一添加到链中。也许这会有所帮助:

    .retryWhen(Retry.fixedDelay(3, Duration.ofSeconds(3)))
    

    Example from reactor reference documentation

    【讨论】:

    • 比较复杂,我应该检查他们的答案字段是否为非空。
    • @EngineerTop 如果您有其他要求,请在问题中包含这些要求,以便我们避免人们进行研究和回答不符合要求的问题。
    猜你喜欢
    • 1970-01-01
    • 2017-05-15
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多