1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package org.apache.hc.client5.http.examples;
28
29 import org.apache.hc.client5.http.classic.methods.HttpGet;
30 import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
31 import org.apache.hc.client5.http.impl.classic.HttpClients;
32 import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
33 import org.apache.hc.core5.http.io.entity.EntityUtils;
34 import org.apache.hc.core5.http.message.StatusLine;
35 import org.apache.hc.core5.pool.PoolStats;
36 import org.apache.hc.core5.util.TimeValue;
37
38
39
40
41
42 public class ClientEvictExpiredConnections {
43
44 public static void main(final String[] args) throws Exception {
45 final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
46 cm.setMaxTotal(100);
47 try (final CloseableHttpClient httpclient = HttpClients.custom()
48 .setConnectionManager(cm)
49 .evictExpiredConnections()
50 .evictIdleConnections(TimeValue.ofSeconds(5))
51 .build()) {
52
53 final String[] urisToGet = {
54 "http://hc.apache.org/",
55 "http://hc.apache.org/httpcomponents-core-ga/",
56 "http://hc.apache.org/httpcomponents-client-ga/",
57 };
58
59 for (final String requestURI : urisToGet) {
60 final HttpGet request = new HttpGet(requestURI);
61
62 System.out.println("Executing request " + request.getMethod() + " " + request.getRequestUri());
63
64 httpclient.execute(request, response -> {
65 System.out.println("----------------------------------------");
66 System.out.println(request + "->" + new StatusLine(response));
67 EntityUtils.consume(response.getEntity());
68 return null;
69 });
70 }
71
72 final PoolStats stats1 = cm.getTotalStats();
73 System.out.println("Connections kept alive: " + stats1.getAvailable());
74
75
76 Thread.sleep(10000);
77
78 final PoolStats stats2 = cm.getTotalStats();
79 System.out.println("Connections kept alive: " + stats2.getAvailable());
80
81 }
82 }
83
84 }