如何限制 spring-webflux WebClient 中打开的套接字数量?

How to limit number of open sockets in spring-webflux WebClient?

我有一些 RESTful 服务,我想用 Reactor 和 Spring WebClient 准备简单的性能基准。 Benchmark 简单地创建 N 个用户,然后为每个创建的用户 post M 票。

不幸的是,在我的 linux 机器中,以下代码超出了最大打开文件限制,即 1024 (ulimit -n 1024)。

    RestService restService = ...
    int N_ITERATIONS = 100;
    int M_VOTES = 100;

    Flux.range(0, N_ITERATIONS)
            .parallel()
            .runOn(Schedulers.parallel())
            .flatMap(iteration -> restService.postUserRegistration(User.builder().build()))
            .flatMap(user -> Flux.range(0, M_VOTES)
                    .flatMap(vote -> restService.postUserVote(Vote.builder().build()))
                    .collectList()
                    .map(votes -> Tuple.of(user, votes))
            ).doOnNext(userVotes -> log.info("User: {} voted: {}", userVotes._1(), userVotes._2()))
            .sequential()
            .toIterable();

RestService 使用来自 Spring Webflux 的标准 WebClient 实现。

有没有办法根据系统限制限制创建的套接字数量?

堆栈跟踪:

Caused by: io.netty.channel.unix.Errors$NativeIoException: newSocketStream(..) failed: Too many open files
    at io.netty.channel.unix.Errors.newIOException(Errors.java:122) ~[netty-transport-native-unix-common-4.1.27.Final.jar:4.1.27.Final]
    ... 98 common frames omitted

我认为没有。但是你可以采取措施来防止它。

首先,为什么你的文件描述符限制这么低? Linux 为每个打开的套接字打开一个文件描述符,因此如果您打算同时拥有大量打开的套接字,则 1024 非常低。我会考虑大大提高这个限制。

其次,您将并发配置留给了调度程序。您应该知道 flatMap 运算符有一个变体,它允许您控制可以并行订阅和合并多少 Publisher

Flux<V> flatMap(
            Function<? super T,? extends Publisher<? extends V>> mapper,
            int concurrency)

使用 concurrency 参数,您可以定义要允许的飞行序列数。