我正在运行一个 Spring Boot 应用程序,它使用 WebClient 来处理非阻塞和阻塞 HTTP 请求。应用程序运行一段时间后,所有传出的 HTTP 请求似乎都会被卡住。
WebClient 用于向多个主机发送请求,但作为示例,以下是它的初始化和用于向 Telegram 发送请求的方式:
网络客户端配置:
@Bean
public ReactorClientHttpConnector httpClient() {
HttpClient.create(ConnectionProvider.builder("connectionProvider").build())
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout)
.responseTimeout(Duration.ofMillis(responseTimeout));
return new ReactorClientHttpConnector(httpClient);
}
Run Code Online (Sandbox Code Playgroud)
所有 WebClient 使用相同的 ReactorClientHttpConnector。
电报客户端:
@Autowired
ReactorClientHttpConnector httpClient;
WebClient webClient;
RateLimiter rateLimiter;
@PostConstruct
public void init() {
webClient = WebClient.builder()
.clientConnector(httpClient)
.baseUrl(telegramUrl)
.build();
rateLimiter = RateLimiter.of("telegram-rate-limiter",
RateLimiterConfig.custom()
.limitRefreshPeriod(Duration.ofMinutes(1))
.limitForPeriod(20)
.build());
}
public void sendMessage(@PathVariable("token") String token, @RequestParam("chat_id") long chatId, @RequestParam("text") String message) {
webClient.post().uri(String.format("/bot%s/sendMessage", token))
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromFormData("chat_id", String.valueOf(chatId))
.with("text", message))
.retrieve()
.bodyToMono(Void.class) …Run Code Online (Sandbox Code Playgroud)