Reactor Flux flatMap操作员的吞吐量/并发控制并实现背压

问题描述 投票:1回答:1

我正在使用Flux建立我的反应性管道。在管道中,我需要调用3个不同的外部系统REST API,它们的访问率非常严格。如果我突破了每秒速率阈值,我将成倍地受到节制。每个系统都有自己的阈值。

我正在使用Spring WebClient进行REST API调用;在3个API中,其中2个是GET,1个是POST。

在我的反应堆管道中,WebClient被包装在flatMap中以执行API调用,如下面的代码:

WebClient getApiCall1 = WebClient.builder().build().get("api-system-1").retrieve().bodyToMono(String.class) //actual return DTO is different from string
WebClient getApiCall2 = WebClient.builder().build().get("api-system-2").retrieve().bodyToMono(String.class) //actual return DTO is different from string
WebClient getApiCall3 = WebClient.builder().build().get("api-system-3").retrieve().bodyToMono(String.class) //actual return DTO is different from string

    Flux.generator(generator) // Generator pushes the elements from source 1 at a time

    // make call to 1st API Service
    .flatMap(data -> getApiCall1)
    .map(api1Response -> api1ResponseModified)

    // make call to 2nd API Service
    .flatMap(api1ResponseModified -> getApiCall2)
    .map(api2Response -> api2ResponseModified)

// make call to 3rd API Service
.flatMap(api2ResponseModified -> getApiCall3)
.map(api3Response -> api3ResponseModified)

// rest of the pipeline operators

//end
.subscriber();

问题是,如果不将concurrency值设置为flatMap,则流水线执行将在服务启动后几秒钟内突破阈值。如果将concurrency的值设置为1、2、5、10,则吞吐量将变得非常低。

问题是,在不为并发设置任何值的情况下,我如何实现应符合外部系统速率限制的背压?

spring-boot spring-webflux project-reactor reactive-streams spring-webclient
1个回答
0
投票

我会使用类似的东西:

public static <T> Flux<T> limitIntervalRate(Flux<T> flux, int ratePerInterval, Duration interval) {
    return flux
            .window(ratePerInterval)
            .zipWith(Flux.interval(Duration.ZERO, interval))
            .flatMap(Tuple2::getT1);
}

允许您执行以下操作:

sourceFlux
        .transform(f -> limitIntervalRate(f, 10, Duration.ofSeconds(1))) //Limit to a rate of 10 per second

然后您可以根据需要将其映射到您的WebClient呼叫上,同时遵守适当的限制。

© www.soinside.com 2019 - 2024. All rights reserved.