【问题标题】:Limiting rate of requests with Reactor使用 Reactor 限制请求的速率
【发布时间】:2017-10-03 15:17:32
【问题描述】:

我正在使用项目反应器从使用 REST 的 Web 服务加载数据。这是与多个线程并行完成的。我开始达到网络服务的速率限制,所以我想每秒最多发送 10 个请求以避免出现这些错误。我将如何使用反应器来做到这一点?

使用 zipWith(Mono.delayMillis(100))?还是有更好的办法?

谢谢

【问题讨论】:

  • 当前解决方案:Flux.range(1, 10) .zipWith(Flux.interval(Duration.of(1, ChronoUnit.SECONDS))) .map(Tuple2::getT1) .toIterable() .forEach(i -> logger.info("Received: {}", i));

标签: java project-reactor


【解决方案1】:

您可以使用delayElements 而不是整个zipwith

【讨论】:

  • 是否可以从 Flux 中获取响应?
【解决方案2】:

下面的代码将以每秒 10 个请求的速率对 https://www.google.com/ 执行 GET。您必须进行额外的更改以支持您的服务器无法在 1 秒内处理所有 10 个请求的情况;当您的服务器仍在处理前一秒提出的请求时,您可以跳过发送请求。

@Test
void parallelHttpRequests() {
    // this is just for limiting the test running period otherwise you don't need it
    int COUNT = 2;

    // use whatever (blocking) http client you desire;
    // when using e.g. WebClient (Spring, non blocking client)
    // the example will slightly change for no longer use
    // subscribeOn(Schedulers.elastic())
    RestTemplate client = new RestTemplate();
    
    var exit = new AtomicBoolean(false);
    var lock = new ReentrantLock();
    var condition = lock.newCondition();

    MessageFormat message = new MessageFormat("#batch: {0}, #req: {1}, resultLength: {2}");
    Flux.interval(Duration.ofSeconds(1L))
            .take(COUNT) // this is just for limiting the test running period otherwise you don't need it
            .doOnNext(batch -> debug("#batch", batch)) // just for debugging
            .flatMap(batch -> Flux.range(1, 10) // 10 requests per 1 second
                            .flatMap(i -> Mono.fromSupplier(() ->
                                    client.getForEntity("https://www.google.com/", String.class).getBody()) // your request goes here (1 of 10)
                                    .map(s -> message.format(new Object[]{batch, i, s.length()})) // here the request's result will be the output of message.format(...)
                                    .doOnSubscribe(s -> debug("doOnSubscribe: #batch = " + batch + ", i = " + i)) // just for debugging
                                    .subscribeOn(Schedulers.elastic()) // one I/O thread per request
                            )
            )
            .subscribe(
                    s -> debug("received", s) // do something with the above request's result
                    e -> {
                        debug("error", e.getMessage());
                        signalAll(exit, condition, lock);
                    },
                    () -> {
                        debug("done");
                        signalAll(exit, condition, lock);
                    }
            );

    await(exit, condition, lock);
}

// most probably you won't need the "await" and "signalAll" methods below but
// I created them anyway just to be easier for one to run this in a test class

private void await(AtomicBoolean exit, Condition condition, Lock lock) {
    lock.lock();
    while (!exit.get()) {
        try {
            condition.await();
        } catch (InterruptedException e) {
            // maybe spurious wakeup
            e.printStackTrace();
        }
    }
    lock.unlock();
    debug("exit");
}

private void signalAll(AtomicBoolean exit, Condition condition, Lock lock) {
    exit.set(true);
    try {
        lock.lock();
        condition.signalAll();
    } finally {
        lock.unlock();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 2013-12-13
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 2012-09-03
    相关资源
    最近更新 更多