0
# Connection Management
1
2
Apache HttpClient provides sophisticated connection management capabilities for efficient resource utilization, connection pooling, and performance optimization. This includes both pooled and basic connection managers with comprehensive lifecycle control.
3
4
## Connection Manager Interface
5
6
### HttpClientConnectionManager
7
8
```java { .api }
9
public interface HttpClientConnectionManager {
10
ConnectionRequest requestConnection(HttpRoute route, Object state);
11
void releaseConnection(HttpClientConnection conn, Object newState, long validDuration, TimeUnit timeUnit);
12
void connect(HttpClientConnection conn, HttpRoute route, int connectTimeout, HttpContext context) throws IOException;
13
void upgrade(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException;
14
void routeComplete(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException;
15
void closeExpiredConnections();
16
void closeIdleConnections(long idletime, TimeUnit tunit);
17
void shutdown();
18
}
19
```
20
21
Main interface for managing HTTP client connections with lifecycle control methods.
22
23
### ConnectionRequest
24
25
```java { .api }
26
public interface ConnectionRequest {
27
HttpClientConnection get(long timeout, TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectTimeoutException;
28
boolean cancel();
29
}
30
```
31
32
Represents a request for a connection that may be fulfilled asynchronously.
33
34
## Pooling Connection Manager
35
36
### PoolingHttpClientConnectionManager
37
38
```java { .api }
39
public class PoolingHttpClientConnectionManager implements HttpClientConnectionManager, ConnPoolControl<HttpRoute> {
40
public PoolingHttpClientConnectionManager();
41
public PoolingHttpClientConnectionManager(HttpClientConnectionOperator httpClientConnectionOperator);
42
public PoolingHttpClientConnectionManager(HttpClientConnectionOperator httpClientConnectionOperator,
43
HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory,
44
long timeToLive, TimeUnit tunit);
45
public PoolingHttpClientConnectionManager(Registry<ConnectionSocketFactory> socketFactoryRegistry);
46
public PoolingHttpClientConnectionManager(Registry<ConnectionSocketFactory> socketFactoryRegistry,
47
DnsResolver dnsResolver);
48
public PoolingHttpClientConnectionManager(Registry<ConnectionSocketFactory> socketFactoryRegistry,
49
HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory);
50
public PoolingHttpClientConnectionManager(Registry<ConnectionSocketFactory> socketFactoryRegistry,
51
HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory,
52
DnsResolver dnsResolver);
53
}
54
```
55
56
Connection manager that maintains a pool of connections for reuse across multiple requests.
57
58
### Pool Configuration Methods
59
60
```java { .api }
61
public void setMaxTotal(int max);
62
public int getMaxTotal();
63
public void setDefaultMaxPerRoute(int max);
64
public int getDefaultMaxPerRoute();
65
public void setMaxPerRoute(HttpRoute route, int max);
66
public int getMaxPerRoute(HttpRoute route);
67
public PoolStats getTotalStats();
68
public PoolStats getStats(HttpRoute route);
69
```
70
71
Methods for configuring connection pool limits and retrieving statistics.
72
73
Example usage:
74
75
```java
76
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
77
cm.setMaxTotal(100); // Maximum total connections
78
cm.setDefaultMaxPerRoute(20); // Maximum connections per route
79
cm.setMaxPerRoute(new HttpRoute(new HttpHost("api.example.com")), 50);
80
81
CloseableHttpClient httpClient = HttpClients.custom()
82
.setConnectionManager(cm)
83
.build();
84
```
85
86
### Connection Eviction
87
88
```java { .api }
89
public void closeExpiredConnections();
90
public void closeIdleConnections(long idletime, TimeUnit tunit);
91
public void shutdown();
92
```
93
94
Methods for cleaning up expired and idle connections.
95
96
```java
97
// Close connections that have been idle for more than 30 seconds
98
cm.closeIdleConnections(30, TimeUnit.SECONDS);
99
100
// Close expired connections
101
cm.closeExpiredConnections();
102
```
103
104
## Basic Connection Manager
105
106
### BasicHttpClientConnectionManager
107
108
```java { .api }
109
public class BasicHttpClientConnectionManager implements HttpClientConnectionManager {
110
public BasicHttpClientConnectionManager();
111
public BasicHttpClientConnectionManager(HttpClientConnectionOperator httpClientConnectionOperator);
112
public BasicHttpClientConnectionManager(Registry<ConnectionSocketFactory> socketFactoryRegistry);
113
public BasicHttpClientConnectionManager(Registry<ConnectionSocketFactory> socketFactoryRegistry,
114
HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory);
115
public BasicHttpClientConnectionManager(Registry<ConnectionSocketFactory> socketFactoryRegistry,
116
HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory,
117
SchemePortResolver schemePortResolver,
118
DnsResolver dnsResolver);
119
}
120
```
121
122
Simple connection manager that maintains only a single connection at a time.
123
124
```java
125
BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager();
126
CloseableHttpClient httpClient = HttpClients.custom()
127
.setConnectionManager(cm)
128
.build();
129
```
130
131
## Connection Configuration
132
133
### Connection Socket Factories
134
135
```java { .api }
136
public interface ConnectionSocketFactory {
137
Socket createSocket(HttpContext context) throws IOException;
138
Socket connectSocket(int connectTimeout, Socket sock, HttpHost host,
139
InetSocketAddress remoteAddress, InetSocketAddress localAddress,
140
HttpContext context) throws IOException;
141
}
142
```
143
144
Interface for creating and configuring connection sockets.
145
146
### Plain Connection Socket Factory
147
148
```java { .api }
149
public class PlainConnectionSocketFactory implements ConnectionSocketFactory {
150
public static PlainConnectionSocketFactory getSocketFactory();
151
public Socket createSocket(HttpContext context) throws IOException;
152
public Socket connectSocket(int connectTimeout, Socket sock, HttpHost host,
153
InetSocketAddress remoteAddress, InetSocketAddress localAddress,
154
HttpContext context) throws IOException;
155
}
156
```
157
158
Factory for creating plain (non-SSL) connections.
159
160
### SSL Connection Socket Factory
161
162
```java { .api }
163
public class SSLConnectionSocketFactory implements LayeredConnectionSocketFactory {
164
public static SSLConnectionSocketFactory getSocketFactory();
165
public static SSLConnectionSocketFactory getSystemSocketFactory();
166
public SSLConnectionSocketFactory(SSLContext sslContext);
167
public SSLConnectionSocketFactory(SSLContext sslContext, HostnameVerifier hostnameVerifier);
168
public SSLConnectionSocketFactory(SSLContext sslContext, String[] supportedProtocols,
169
String[] supportedCipherSuites, HostnameVerifier hostnameVerifier);
170
}
171
```
172
173
Factory for creating SSL/TLS connections.
174
175
Example configuration:
176
177
```java
178
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
179
.register("http", PlainConnectionSocketFactory.getSocketFactory())
180
.register("https", SSLConnectionSocketFactory.getSystemSocketFactory())
181
.build();
182
183
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
184
```
185
186
## Connection Pool Statistics
187
188
### PoolStats
189
190
```java { .api }
191
public class PoolStats {
192
public int getLeased();
193
public int getPending();
194
public int getAvailable();
195
public int getMax();
196
}
197
```
198
199
Statistics for connection pool state.
200
201
Example usage:
202
203
```java
204
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
205
// ... perform requests ...
206
207
PoolStats totalStats = cm.getTotalStats();
208
System.out.println("Leased connections: " + totalStats.getLeased());
209
System.out.println("Pending requests: " + totalStats.getPending());
210
System.out.println("Available connections: " + totalStats.getAvailable());
211
System.out.println("Max connections: " + totalStats.getMax());
212
```
213
214
## Connection Lifecycle Management
215
216
### ManagedHttpClientConnection
217
218
```java { .api }
219
public interface ManagedHttpClientConnection extends HttpClientConnection, HttpInetConnection {
220
String getId();
221
void bind(Socket socket) throws IOException;
222
Socket getSocket();
223
SSLSession getSSLSession();
224
}
225
```
226
227
Interface representing a managed HTTP client connection.
228
229
### Connection Requests
230
231
```java { .api }
232
public interface ConnectionRequest {
233
HttpClientConnection get(long timeout, TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectTimeoutException;
234
boolean cancel();
235
}
236
```
237
238
Represents an asynchronous request for a connection.
239
240
## Route Management
241
242
### HttpRoute
243
244
```java { .api }
245
public final class HttpRoute implements Cloneable {
246
public HttpRoute(HttpHost target);
247
public HttpRoute(HttpHost target, InetAddress localAddress, HttpHost proxy, boolean secure);
248
public HttpHost getTargetHost();
249
public HttpHost getProxyHost();
250
public int getHopCount();
251
public HttpHost getHopTarget(int hop);
252
public boolean isSecure();
253
public boolean isTunnelled();
254
public boolean isLayered();
255
}
256
```
257
258
Represents the route that a request will take to reach the target server.
259
260
### RouteInfo Interface
261
262
```java { .api }
263
public interface RouteInfo {
264
HttpHost getTargetHost();
265
HttpHost getProxyHost();
266
int getHopCount();
267
HttpHost getHopTarget(int hop);
268
boolean isSecure();
269
TunnelType getTunnelType();
270
LayerType getLayerType();
271
}
272
```
273
274
Information about the route to a target host.
275
276
## Connection Keep-Alive
277
278
### Connection Keep-Alive Strategy
279
280
```java { .api }
281
public interface ConnectionKeepAliveStrategy {
282
long getKeepAliveDuration(HttpResponse response, HttpContext context);
283
}
284
```
285
286
Strategy for determining connection keep-alive duration.
287
288
Example implementation:
289
290
```java
291
ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() {
292
@Override
293
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
294
HeaderElementIterator it = new BasicHeaderElementIterator(
295
response.headerIterator(HTTP.CONN_KEEP_ALIVE));
296
while (it.hasNext()) {
297
HeaderElement he = it.nextElement();
298
String param = he.getName();
299
String value = he.getValue();
300
if (value != null && param.equalsIgnoreCase("timeout")) {
301
return Long.parseLong(value) * 1000;
302
}
303
}
304
return 5 * 1000; // Default to 5 seconds
305
}
306
};
307
308
CloseableHttpClient httpClient = HttpClients.custom()
309
.setKeepAliveStrategy(keepAliveStrategy)
310
.build();
311
```
312
313
## Types
314
315
### ConnPoolControl
316
317
```java { .api }
318
public interface ConnPoolControl<T> {
319
void setMaxTotal(int max);
320
int getMaxTotal();
321
void setDefaultMaxPerRoute(int max);
322
int getDefaultMaxPerRoute();
323
void setMaxPerRoute(T route, int max);
324
int getMaxPerRoute(T route);
325
PoolStats getTotalStats();
326
PoolStats getStats(T route);
327
}
328
```
329
330
Interface for controlling connection pool configuration.