这里的cache storage 采用ehcache,而不是默认的内存式的cache storage。采用ehcache可以将内容缓存到磁盘上。

maven

        <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient-cache</artifactId>
<version>4.5</version>
</dependency> <dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.8.3</version>
</dependency>

ehcache配置如下:

<ehcache>
<!-- <diskStore path="java.io.tmpdir" /> --> <diskStore path="c:\\ehcache"/> <defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" /> <cache name="httpCache"
maxElementsInMemory="10000"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="true"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" />
</ehcache>

这里有两个关键点:一是将eternal设置为true,表示采用非内存式的缓存;二是将diskPersistent设置为true,表示将缓存持久化到硬盘。

测试的代码如下:

package my.httpClient;

import java.io.IOException;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.Configuration;
import net.sf.ehcache.config.DiskStoreConfiguration;
import net.sf.ehcache.config.PersistenceConfiguration;
import net.sf.ehcache.config.PersistenceConfiguration.Strategy;
import net.sf.ehcache.store.MemoryStoreEvictionPolicy; import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.cache.CacheResponseStatus;
import org.apache.http.client.cache.HttpCacheContext;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.cache.CacheConfig;
import org.apache.http.impl.client.cache.CachingHttpClients;
import org.apache.http.impl.client.cache.ehcache.EhcacheHttpCacheStorage; public class EhCacheTest1 { public static void main(String[] args) throws ClientProtocolException,
IOException { System.out.println("begin"); // EhCache缓存存储
CacheManager cacheManager = CacheManager.create();
Cache httpCache = cacheManager.getCache("httpCache"); // 定义httpclient的缓存存储
EhcacheHttpCacheStorage ehcacheHttpCacheStorage = new EhcacheHttpCacheStorage(
httpCache); // 缓存配置
CacheConfig cacheConfig = CacheConfig.custom()
.setMaxCacheEntries(10000).setMaxObjectSize(819200).build(); RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(30000).setSocketTimeout(30000).build(); HttpHost proxy = new HttpHost("127.0.0.1", 8888); CloseableHttpClient cachingClient = CachingHttpClients.custom()
.setCacheConfig(cacheConfig)
.setHttpCacheStorage(ehcacheHttpCacheStorage)
.setDefaultRequestConfig(requestConfig).setProxy(proxy).build(); HttpCacheContext context = HttpCacheContext.create();
HttpGet httpget = new HttpGet("http://test.cn:11677/api/values?id=8888"); CloseableHttpResponse response = cachingClient
.execute(httpget, context);
try {
CacheResponseStatus responseStatus = context
.getCacheResponseStatus();
switch (responseStatus) {
case CACHE_HIT:
System.out
.println("A response was generated from the cache with "
+ "no requests sent upstream");
break;
case CACHE_MODULE_RESPONSE:
System.out
.println("The response was generated directly by the "
+ "caching module");
break;
case CACHE_MISS:
System.out.println("The response came from an upstream server");
break;
case VALIDATED:
System.out.println("The response was generated from the cache "
+ "after validating the entry with the origin server");
break;
}
} catch (Exception e) {
// TODO: handle exception } finally {
response.close();
cacheManager.shutdown();
System.out.println("end");
}
} }

以上代码有几个需要说明的地方:

(1)服务端需要遵循RFC2626中规定缓存方面的协议。

(2)代码setHttpCacheStorage(ehcacheHttpCacheStorage)用于设置缓存存储。

(3)代码setProxy(proxy)用于配置代理,当你使用fiddler进行调试的时候,这个很有用。若不采用代理,则可以将这句给去掉。

(4)代码cacheManager.shutdown()用于关闭cacheManager,记得一定要执行这一句,否则会报错。

apache httpclient cache 实现可缓存的http客户端的更多相关文章

  1. 如何在Apache HttpClient中设置TLS版本

    1.简介 Apache HttpClient是一个底层.轻量级的客户端HTTP库,用于与HTTP服务器进行通信. 在本教程中,我们将学习如何在使用HttpClient时配置支持的传输层安全(TLS)版 ...

  2. android 中对apache httpclient及httpurlconnection的选择

    在官方blog中,android工程师谈到了如何去选择apache client和httpurlconnection的问题: 原文见http://android-developers.blogspot ...

  3. Zookeeper + Guava loading cache 实现分布式缓存

    1. 概述 项目中,创建的活动内容存入redis,然后需要用到活动内容的地方,从redis去取,然后参与计算. 活动数据的一个特点是更新不频繁.数据量不大.因为项目部署一般是多机器.多实例,除了red ...

  4. org.springframework.beans.MethodInvocationException: Property 'cacheManager' threw exception; nested exception is org.apache.shiro.cache.CacheException: net.sf.ehcache.CacheException: Caches cannot be

    shiro cache manage配置报错: org.springframework.beans.MethodInvocationException: Property 'cacheManager' ...

  5. [.net 面向对象程序设计进阶] (15) 缓存(Cache)(二) 利用缓存提升程序性能

    [.net 面向对象程序设计进阶] (15) 缓存(Cache)(二) 利用缓存提升程序性能 本节导读: 上节说了缓存是以空间来换取时间的技术,介绍了客户端缓存和两种常用服务器缓布,本节主要介绍一种. ...

  6. [.net 面向对象程序设计进阶] (14) 缓存(Cache) (一) 认识缓存技术

    [.net 面向对象程序设计进阶] (14) 缓存(Cache)(一) 认识缓存技术 本节导读: 缓存(Cache)是一种用空间换时间的技术,在.NET程序设计中合理利用,可以极大的提高程序的运行效率 ...

  7. 在android 6.0(API 23)中,Google已经移除了移除了Apache HttpClient相关的类

    推荐使用HttpUrlConnection,如果要继续使用需要Apache HttpClient,需要在eclipse下libs里添加org.apache.http.legacy.jar,androi ...

  8. 论httpclient上传带参数【commons-httpclient和apache httpclient区别】

    需要做一个httpclient上传,然后啪啪啪网上找资料 1.首先以前系统中用到的了commons-httpclient上传,找了资料后一顿乱改,然后测试 PostMethod filePost = ...

  9. Apache HttpClient使用之阻塞陷阱

    前言: 之前做个一个数据同步的定时程序. 其内部集成了某电商的SDK(简单的Apache Httpclient4.x封装)+Spring Quartz来实现. 原本以为简单轻松, 喝杯咖啡就高枕无忧的 ...

随机推荐

  1. 清除WKWebView的缓存

    OC写法: swift写法再下下面. 清除WKWebView的缓存,让H5页面一刷新就更新至最新的页面 要区分iOS9.0和8.0两种 - (void)deleteWebCache { if ([[U ...

  2. Python切片

    切片是啥, 可以吃么 切片肿么用哈 辣么长,记不住 切片是啥, 可以吃么 嘛,所谓切片故名思意就有选取的意思啦, 跟java里面的subString()意思差不多, 从原始的字符串中按规则提取出新的字 ...

  3. IosPush推送通知的实现

    1. Apple推送通知的机制 上图可以分为三个阶段: 第一阶段:应用程序把要发送的消息.目的iPhone的标识打包,发给APNS. 第二阶段:APNS在自身的已注册Push服务的iPhone列表中, ...

  4. Laravel 学习笔记 —— 神奇的服务容器 [转]

    容器,字面上理解就是装东西的东西.常见的变量.对象属性等都可以算是容器.一个容器能够装什么,全部取决于你对该容器的定义.当然,有这样一种容器,它存放的不是文本.数值,而是对象.对象的描述(类.接口)或 ...

  5. gcc与gdb版本兼容问题

    今天在用gdb调试C++程序的时候,想用"p i”命令打印出程序的一个局部变量i,却一直提示: No symbol "i" in current context. 我愣了 ...

  6. c# udp局域网通信

    udp224.0.0.1 子网上的所有系统224.0.0.2 子网上的所有路由器224.0.0.12 dhcp服务器224.0.1.1 ntp224.0.1.24 wins服务器 http://www ...

  7. 读书笔记——body and html

    在看<常见标签的默认属性值及相互作用——关于CSS reset的思考>的时候,其中说body默认的margin是8px.但是,将body的backgound-color:red:后,看到的 ...

  8. 大前端学习笔记整理【七】HTTP协议以及http与https的区别

    前言 还是老样子,新博客开始前总是想先啰嗦几句...HTTP协议其实在当初学习java时老师就有提过...但是...反正就那么过去了... 这段时间公司的项目正好要求做https的转换和迁移,然后自己 ...

  9. ubuntu14.04设置terminal配色方案以配合使用vim的Solarized插件

    在安装vim插件之前,首先安装Vundle插件,用来管理vim插件,安装方法查看Vundle在github上的指南.在安装vundle的时候出现了一个错误E117:unknown function v ...

  10. [PL/SQL] 如何规避异常ORA-01403

    如果mytable表中不存在 ID = 123 的数据,那么 SELECT Flag INTO flag FROM mytable WHERE ID = 123 将抛出异常ORA-01403 SELE ...