ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

spring – 如何使用WebClient限制请求/秒?

2019-10-08 12:22:32  阅读:289  来源: 互联网

标签:project-reactor spring-webflux spring


我正在使用WebClient对象将Http Post请求发送到服务器.
它正在快速发送大量请求(QueueChannel中有大约4000条消息).问题是……似乎服务器响应速度不够快……所以我得到了很多服务器错误500和connexion过早关闭.

有没有办法限制每秒的请求数量?或者限制它使用的线程数量?

编辑:

QueueChannel中的Message endpoint processe消息:

@MessageEndpoint
public class CustomServiceActivator {

    private static final Logger logger = LogManager.getLogger();

    @Autowired
    IHttpService httpService;

    @ServiceActivator(
            inputChannel = "outputFilterChannel",
            outputChannel = "outputHttpServiceChannel",
            poller = @Poller( fixedDelay = "1000" )
    )
    public void processMessage(Data data) {
        httpService.push(data);
        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

WebClient服务类:

@Service
public class HttpService implements IHttpService {

    private static final String URL = "http://www.blabla.com/log";

    private static final Logger logger = LogManager.getLogger();

    @Autowired
    WebClient webClient;

    @Override
    public void push(Data data) {
        String body = constructString(data);
        Mono<ResponseEntity<Response>> res = webClient.post()
                .uri(URL + getLogType(data))
                .contentLength(body.length())
                .contentType(MediaType.APPLICATION_JSON)
                .syncBody(body)
                .exchange()
                .flatMap(response -> response.toEntity(Response.class));

        res.subscribe(new Consumer<ResponseEntity<Response>>() { ... });
    }
}

解决方法:

问题Limiting rate of requests with Reactor提供了两个答复者(一个在评论中)

zipWith另一种作为速率限制器的通量

.zipWith(Flux.interval(Duration.of(1,ChronoUnit.SECONDS)))

只是推迟每个网络请求

使用delayElements函数

编辑:下面的答案对于阻止RestTemplate有效,但不太适合反应模式.

WebClient无法限制请求,但您可以使用合成轻松添加此功能.

您可以使用Guava /中的RateLimiter从外部限制客户端
(https://google.github.io/guava/releases/19.0/api/docs/index.html?com/google/common/util/concurrent/RateLimiter.html)

在本教程http://www.baeldung.com/guava-rate-limiter中,您将了解如何以阻止方式或超时使用速率限制器.

我会装饰所有需要在单独的类中受到限制的调用

>限制每秒的呼叫数
>使用WebClient执行实际的Web调用

标签:project-reactor,spring-webflux,spring
来源: https://codeday.me/bug/20191008/1871594.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有