如何在 Java 中缓存 httpclient 对象?

在我的客户端 webapp 中使用Apache HttpClient 4.5.x,它连接到(并登录到)另一个(比如主)服务器 webapp。

这两个 webapps 之间的关系是多对多的——这意味着对于客户端 webapp 中的某些用户的请求,它必须以另一个用户身份登录 + 在服务器 webapp 中进行休息调用。因此需要对 cookiestore 进行一些分离,并且在创建 httpclient 实例后无法(是否存在?)获取/设置cookie 存储,因此客户端 webapp 中收到的每个请求线程都会执行以下操作(并且需要优化):

HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(new BasicCookieStore()).build();
//Now POST to login end point and get back JSESSIONID cookie and then make one REST call, and then the client object goes out of scope when the request ends.

我希望询问将 httpclient 实例对象缓存为重的最佳实践,并且应该至少为多个请求重用,如果不是将整个客户端 webapp 作为静态单例。

具体来说,我希望就以下哪些(如果有)方法构成最佳实践提供建议:

  1. 使用静态 ConcurrentHashMap为客户端 webapp 中的每个“用户”缓存 httpclient 及其关联的 basiccookiestore,并且仅在包含的缓存 cookie 接近其到期时间时登录。不确定内存使用情况,并且未/很少使用的 httpclient 会留在内存中而不会被驱逐。

  2. 仅缓存 Cookie(以某种方式),但在需要使用该 cookie 进行休息调用时重新创建一个新的 httpclient 对象。这会保存之前的 login 调用,直到 cookie 过期,但不会重用 htptclient。

  3. PooledConnectionManager - 但无法轻松找到示例,尽管可能需要设计驱逐策略、最大线程数等(因此可能很复杂)。

有没有更好的方法来做到这一点?谢谢。


开心每一天1111
浏览 213回答 2
2回答

米琪卡哇伊

使用并发哈希映射将是实现您想要做的最简单的方法。此外,如果您使用 Spring,您可能需要创建一个 bean 来保存 HTTP 客户端。

哈士奇WWW

你为什么要做这一切?CookieStore可以使用 local 为每个请求分配不同的HttpContext.如果需要,可以维护CookieStore每个唯一用户的实例映射。CloseableHttpClient httpclient = HttpClients.createDefault();CookieStore cookieStore = new BasicCookieStore();// Create local HTTP contextHttpClientContext localContext = HttpClientContext.create();// Bind custom cookie store to the local contextlocalContext.setCookieStore(cookieStore);HttpGet httpget = new HttpGet("http://httpbin.org/cookies");System.out.println("Executing request " + httpget.getRequestLine());// Pass local context as a parameterCloseableHttpResponse response = httpclient.execute(httpget, localContext);try {&nbsp; &nbsp; System.out.println("----------------------------------------");&nbsp; &nbsp; System.out.println(response.getStatusLine());&nbsp; &nbsp; List<Cookie> cookies = cookieStore.getCookies();&nbsp; &nbsp; for (int i = 0; i < cookies.size(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Local cookie: " + cookies.get(i));&nbsp; &nbsp; }&nbsp; &nbsp; EntityUtils.consume(response.getEntity());} finally {&nbsp; &nbsp; response.close();}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java