springでは、単一のインターフェイスのタイムアウトを設定する方法はありますか?

Springで、特定のインターフェースのタイムアウトを設定するには、RestTemplateやWebClientを使用することができます。以下は、それぞれの方法の例です:

  1. レストテンプレート
// 创建一个带有连接和读取超时时间的HttpComponentsClientHttpRequestFactory
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setConnectTimeout(5000); // 设置连接超时时间为5000毫秒
factory.setReadTimeout(5000); // 设置读取超时时间为5000毫秒

// 创建RestTemplate并设置请求工厂
RestTemplate restTemplate = new RestTemplate(factory);

// 发起HTTP请求
String url = "http://example.com/api/endpoint";
String response = restTemplate.getForObject(url, String.class);
  1. Web クライアント
// 创建一个带有连接和读取超时时间的HttpClient
HttpClient httpClient = HttpClient.create()
        .tcpConfiguration(tcpClient ->
                tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000) // 设置连接超时时间为5000毫秒
                        .doOnConnected(conn -> conn
                                .addHandlerLast(new ReadTimeoutHandler(5)))); // 设置读取超时时间为5秒

// 创建WebClient并设置HTTP客户端
WebClient webClient = WebClient.builder()
        .clientConnector(new ReactorClientHttpConnector(httpClient))
        .build();

// 发起HTTP请求
String url = "http://example.com/api/endpoint";
Mono<String> response = webClient.get()
        .uri(url)
        .retrieve()
        .bodyToMono(String.class);

これらの方法のどちらも、個々のインターフェースのタイムアウト時間を設定するために使用することができます。具体的な要件に応じて、どちらかの方法を選択して実装することができます。

bannerAds