这里的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. sublime插件 TortioseSVN

    TortioseSVN 可以安装在sublime中,实现svn文件的增加.删除.更新.提交等功能(TortioseSVN用在window系统中,linux安装svn) 安装: 首先在sublime中搜 ...

  2. DIV页面布局,开局代码

    DIV页面布局,开局代码 主要是style部分和body部分 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN ...

  3. php和syslog

    syslog是Linux系统默认的日志守护进程.使用syslog可以方便把指定的事件写入特定文件中,可以让任何事件都登录到一台或多台服务器上. 1.简单例子,先说一下syslog怎么使用,以php为例 ...

  4. 如何去掉div滚动条

    1.去掉横向滚动条 style="overflow-x:hidden" 2.去掉纵向滚动条 style="overflow-y:hidden" 3.同时去掉横向 ...

  5. 1282 - Leading and Trailing ---LightOj1282(快速幂 + 数学)

    http://lightoj.com/volume_showproblem.php?problem=1282 题目大意: 求n的k次方的前三位和后三位数然后输出 后三位是用快速幂做的,我刚开始还是不会 ...

  6. 试图删除 xx 和yy之间的关系。但是,关系的其中一个外键 (xx_yy.xxID) 无法设置为 null。

    错误原因:试图删除 UserInfoGroup 和 UserInfoGroupLinkLimitsOfAuthority 之间的关系.但是,关系的其中一个外键 (UserInfoGroupLinkLi ...

  7. ifmodule

    <IfModule>   指令   说明  封装指令并根据指定的模块是否启用为条件而决定是否进行处理  语法   <IfModule [!]module-file|module-id ...

  8. 时间管理的若干Tips

    时间管理的若干Tips 记下来 再好的记性也不如一支笔与一个本子. 买一支好点的笔于一个好点的本子,让自己有书写的欲望,将todo事项记下来. 小目标 太大太远的目标会使人气馁.通过将大目标分解再分解 ...

  9. Caring for our seniors

    We all have our own journeys to make. And I have been thought that our journeys define us. Some jour ...

  10. php怎么解决超链接中的中文参数转码问题?

    如题,我需要通过前端的网页传递一个中文参数(如:电脑)给后端的PHP文件,传递方式是通过超链接 "index.php/search/keyword/电脑" ,很明显的中文在传递过程 ...