How to limit the request/second with WebClient?

前端 未结 4 1677
日久生厌
日久生厌 2020-12-10 05:50

I\'m using a WebClient object to send Http Post request to a server. It\'s sending a huge amount of requests quite rapidly (there is about 4000 messages in a

4条回答
  •  猫巷女王i
    2020-12-10 06:32

    I use this to limit the number of active requests:

    public DemoClass(WebClient.Builder webClientBuilder) {
        AtomicInteger activeRequest = new AtomicInteger();
        this.webClient = webClientBuilder
                .baseUrl("http://httpbin.org/ip")
                .filter(
                        (request, next) -> Mono.just(next)
                                .flatMap(a -> {
                                    if (activeRequest.intValue() < 3) {
                                        activeRequest.incrementAndGet();
                                        return next.exchange(request)
                                                .doOnNext(b -> activeRequest.decrementAndGet());
                                    }
                                  return Mono.error(new RuntimeException("Too many requests"));
                                })
                                .retryWhen(Retry.anyOf(RuntimeException.class)
                                        .randomBackoff(Duration.ofMillis(300), Duration.ofMillis(1000))
                                        .retryMax(50)
                                )
                )
                .build();
    }
    
    public Mono call() {
        return webClient.get()
                .retrieve()
                .bodyToMono(String.class);
    }
    

提交回复
热议问题