You need to enable JavaScript to run this app. Project Reactor中如何对带延迟元素的并行Flux限流(API请求场景)
优惠活动
大模型
产品
解决方案
定价
更多

Project Reactor中如何对带延迟元素的并行Flux限流(API请求场景)

Project Reactor并行Flux限流实现方案

你遇到的问题根源是默认配置下flatMap没有并发上限,默认允许同时订阅的内层Publisher数量为256,远大于你100个元素的总量,因此所有API请求会同时触发。可以根据你的需求选择以下两种实现方案,全程不需要不合理的block()调用:


方案1:完全串行执行(前一个请求处理完成再发起下一个)

如果严格要求一次只能有一个请求在途,等价于你注释中block()的效果,直接使用concatMap替换flatMap即可,无需使用并行流:

Flux.range(0, 100)
        .concatMap(i -> {
            System.out.println("make api call with huge payload");
            return Mono.just(i).delayElement(Duration.ofMillis((long) (Math.random() * 500 + 500)))
                    .subscribeOn(Schedulers.boundedElastic());
        })
        .doOnNext(i -> {
            //do something with the data
            System.out.println("Got data from request " + i);
        })
        //block for demonstration only so it's copy pasteable
        .blockLast();

concatMap本质是并发度为1的flatMap,会严格等待前一个内层Mono执行完成后才订阅下一个,完全满足串行执行的要求。


方案2:固定并发数限流(平衡性能和服务压力)

如果不需要完全串行,可以通过flatMap的第二参数指定最大并发数,比如同时最多发起5个请求:

Flux.range(0, 100)
        .flatMap(i -> {
            System.out.println("make api call with huge payload");
            return Mono.just(i).delayElement(Duration.ofMillis((long) (Math.random() * 500 + 500)))
                    .subscribeOn(Schedulers.boundedElastic());
        }, 5) // 此处指定最大并发为5,超过阈值的请求会被缓冲等待
        .doOnNext(i -> {
            //do something with the data
            System.out.println("Got data from request " + i);
        })
        //block for demonstration only so it's copy pasteable
        .blockLast();

如果要保留并行流的写法,也可以通过指定parallel()的并行度 + 单Rail内串行实现:

Flux.range(0, 100)
        .parallel(5) // 指定并行度为5,最多同时5个执行链路
        .runOn(Schedulers.boundedElastic())
        .flatMap(i -> {
            System.out.println("make api call with huge payload");
            return Mono.just(i).delayElement(Duration.ofMillis((long) (Math.random() * 500 + 500)));
        }, 1) // 单链路内串行,保证每个链路一次只发起一个请求
        .doOnNext(i -> {
            //do something with the data
            System.out.println("Got data from request " + i);
        })
        .sequential() 
        //block for demonstration only so it's copy pasteable
        .blockLast();

内容的提问来源于stack exchange,提问作者Stezy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 20:15:02