这里的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. 【Debian】非法关机后无法联网 connect: network is unreachable

    某一天,突然发现无法ssh登录虚拟机内的debian系统,一直认为是ssh的问题,然后无意间ping了ping百度,发现原来是debian系统没有联网....囧 首先,是虚拟机的网络设置检查. 打开V ...

  2. js ShowDialogModal 关闭子页面并刷新父页面,保留查询条件

    不知道大家有没有碰到类似的问题,当时的你是什么思路来处理这个问题呢?是url,session,cookie,还是…… 今天笔者就遇到了这个问题,当时的想法如:url,session,cookie都尝试 ...

  3. android BluetoothLE 多个 setCharacteristicNotification writeCharacteristic 失效

    如果在搜索完服务后,执行多个 setCharacteristicNotification 或 writeCharacteristic 操作,某些操作可能会无效.需要在中间等待一些时间,真是一个大坑! ...

  4. 在Sublime Text3上面更加方便愉快的写php

    写php代码,elcipse体积太大,开起来太麻烦,记事本又没有什么标识,稍不留神就会出现;没加.大括号没对全的尴尬情况.所以我选择使用Sublime. 推荐几个 sublime插件:sublimeL ...

  5. mysql日志 解析

    mysql有4种不同的日志,分别是二进制日志,查询日志,慢查询日志和错误日志,这些日记记录着数据库工作的方方面面,可以帮助我们了解数据库的不同方面的踪迹,下面先介绍二进制日志的作用和使用方法,并利用二 ...

  6. Jquery插件开发精品教程

    最开始接触jquery对他提供的各种插件总是十分有兴趣,但是总是不理解为什么这样写,从网络上查询了很久终于找到这篇文章,讲解的很详细,分享给大家. 要说jQuery 最成功的地方,我认为是它的可扩展性 ...

  7. Eclipse在线集成maven M2eclipse插件

    首先说下版本: Eclipse:3.6 Maven:3.3.1,若不知道如何在本地安装Maven,请参见我的另一篇文章:Window下安装Maven 废话少说,直接讲步骤就好: 1.打开eclipse ...

  8. Spring aop 原始的工作原理的理解

    理解完aop的名词解释,继续学习spring aop的工作原理. 首先明确aop到底是什么东西?又如何不违单一原则并实现交叉处理呢? 如果对它的认识只停留在面向切面编程,那就脏了.从oop(Objec ...

  9. oracle exists

    公司项目中有用到exists,感觉挺有用的,拷贝一些感念的东西. “exists”和“in”的效率问题 1) select * from T1 where exists(select 1 from T ...

  10. windows里面的批处理命令不停地处理同一条命令

    最近在设置路由表的时候,为了方便,做了一个批处理 route.bat route delete 0.0.0.0route delete 10.25.0.0route ADD 10.25.0.0 MAS ...