|
| 1 | +package com.baeldung.restclient; |
| 2 | + |
| 3 | +import org.apache.hc.client5.http.config.ConnectionConfig; |
| 4 | +import org.apache.hc.client5.http.config.RequestConfig; |
| 5 | +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; |
| 6 | +import org.apache.hc.client5.http.impl.classic.HttpClients; |
| 7 | +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; |
| 8 | +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder; |
| 9 | +import org.apache.hc.core5.http.io.SocketConfig; |
| 10 | +import org.apache.hc.core5.util.Timeout; |
| 11 | +import org.springframework.context.annotation.Bean; |
| 12 | +import org.springframework.context.annotation.Configuration; |
| 13 | +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; |
| 14 | +import org.springframework.web.client.RestTemplate; |
| 15 | + |
| 16 | +@Configuration |
| 17 | +public class RestTemplateConfiguration { |
| 18 | + |
| 19 | + @Bean |
| 20 | + public RestTemplate restTemplate() { |
| 21 | + try { |
| 22 | + // Timeout configurations |
| 23 | + SocketConfig socketConfig = SocketConfig.custom() |
| 24 | + .setSoTimeout(Timeout.ofSeconds(30)) // Read timeout |
| 25 | + .build(); |
| 26 | + |
| 27 | + ConnectionConfig connectionConfig = ConnectionConfig.custom() |
| 28 | + .setConnectTimeout(Timeout.ofSeconds(30)) // Connect timeout |
| 29 | + .build(); |
| 30 | + |
| 31 | + RequestConfig requestConfig = RequestConfig.custom() |
| 32 | + .setConnectionRequestTimeout(Timeout.ofSeconds(30)) // Pool wait timeout |
| 33 | + .build(); |
| 34 | + |
| 35 | + // Connection pool configuration |
| 36 | + PoolingHttpClientConnectionManager connectionManager = |
| 37 | + PoolingHttpClientConnectionManagerBuilder.create() |
| 38 | + .setMaxConnPerRoute(20) |
| 39 | + .setMaxConnTotal(100) |
| 40 | + .setDefaultSocketConfig(socketConfig) |
| 41 | + .setDefaultConnectionConfig(connectionConfig) |
| 42 | + .build(); |
| 43 | + |
| 44 | + CloseableHttpClient httpClient = HttpClients.custom() |
| 45 | + .setConnectionManager(connectionManager) |
| 46 | + .setDefaultRequestConfig(requestConfig) |
| 47 | + .build(); |
| 48 | + |
| 49 | + return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient)); |
| 50 | + |
| 51 | + } catch (Exception e) { |
| 52 | + throw new IllegalStateException("Failed to configure RestTemplate", e); |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments