Ehcache在很多项目中都出现过,用法也比较简单。一般的加些配置就可以了,而且Ehcache可以对页面、对象、数据进行缓存,同时支持集群/分布式缓存。如果整合Spring、Hibernate也非常的简单,Spring对Ehcache的支持也非常好。EHCache支持内存和磁盘的缓存,支持LRU、LFU和FIFO多种淘汰算法,支持分布式的Cache,可以作为Hibernate的缓存插件。同时它也能提供基于Filter的Cache,该Filter可以缓存响应的内容并采用Gzip压缩提高响应速度。
一、准备工作
导入如下包:ehcache ;commons-logging ; cglib ; asm ; spring的jar包;struts2的jar包
二、添加spring配置文件applicationContext-cache.xml
<?xml version="1.0"encoding="UTF-8"?>
<beansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!--缓存 -->
<bean id="cacheManager"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBea
n">
<propertyname="configLocation">
<value>classpath:ehcache.xml</value>
</property>
</bean>
<bean id="userCache"class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager">
<ref local="cacheManager" />
</property>
<property name="cacheName" value="userCache"/>
</bean>
</beans>
三、添加EhCache配置文件ehcache.xml
<?xml version="1.0"encoding="UTF-8"?>
<ehcache>
<!-- maxElementsInMemory设定内存中创建对象的最大值-->
<!-- eternal设置元素(译注:内存中对象)是否永久驻留。如果是,将忽略超时限制且元素永不消亡-->
<!-- overflowToDisk设置当内存中缓存达到 maxInMemory限制时元素是否可写到磁盘上 -->
<!--timeToIdleSeconds设置某个元素消亡前的停顿时间。
也就是在一个元素消亡之前,两次访问时间的最大时间间隔值。这只能在元素不是永久驻留时有效(译注:如果对象永恒不灭,则设置该属性也无用)。如果该值是 0就意味着元素可以停顿无穷长的时间。
-->
<!-- timeToLiveSeconds为元素设置消亡前的生存时间。也就是一个元素从构建到消亡的最大时间间隔值。 这只能在元素不是永久驻留时有效。-->
<!-- diskPersistent是否disk store在虚拟机启动时持久化。默认为false-->
<!--diskExpiryThreadInterval
Seconds运行disk终结线程的时间,默认为120秒-->
<!--MemoryStore支持三种策略:LRU、LFU、FIFO。
1.LRU:最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清除缓存。
2.LFU:最少被使用,缓存的元素有一个hit属性,hit值最小的将会被清除缓存。
3.FIFO:先进先出-->
<diskStorepath="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="500"
timeToLiveSeconds="1000"
diskPersistent="false"
diskExpiryThreadInterval
Seconds="120"/>
<cachename="userCache" maxElementsInMemory="50000"
maxElementsOnDisk="2000" eternal="false"overflowToDisk="true"
diskSpoolBufferSizeMB="20" timeToIdleSeconds="300"timeToLiveSeconds="600"
memoryStoreEvictionPolic
y="LFU" />
</ehcache>
四、测试类
1、EhCacheProvider.java
public class EhCacheProvider {
privatestatic final Log logger =LogFactory.getLog(EhCacheProvider.class);
privatestatic ClassPathXmlApplicationC
ontext ctxt;
static{
ctxt = newClassPathXmlApplicationC
ontext(
"/applicationContext-cache.xml");
logger.info("初始化缓存");
}
publicstatic Cache getCache(String cacheName) {
return(Cache) ctxt.getBean(cacheName);
}
publicstatic Object getObjectInCache(String cacheName, String key){
Cache ch =getCache(cacheName);
if (null !=ch) {
logger.info("缓存["+cacheName + "]中的对象数量为= " + ch.getSize());
}
Element ele= ch.get(key);
if (ele ==null) {
logger.error("缓存["+cacheName + "]中key为["+key + "]的对象不存在");
returnnull;
} else{
returnele.getValue();
}
}
publicstatic void setObjectInCache(String cacheName, String key, Objectvalue) {
Cache ch =getCache(cacheName);
Element ele= new Element(key, value);
ch.put(ele);
}
publicstatic void delCache(String cacheName) {
Cache ch =getCache(cacheName);
ch.removeAll();
logger.info("清除缓存[" +cacheName + "]内的所有数据。");
}
publicstatic boolean checkKey(String cacheName, String key){
Cache ch =getCache(cacheName);
returnch.getKeys().contains(key);
}
}
2、IehCacheService.java
public interface IehCacheService<T>{
public TgetInCache(String key);
public voidsetInCache(String key, T object);
public voiddelCache();
publicboolean checkKey(String key);
}
3、CacheService.java
public class CacheService implementsIehCacheService<User> {
privatestatic Log log = LogFactory.getLog(UserCacheService.class);
publicstatic final String USER_CACHENAME = "userCache";
public UsergetInCache(String sid) {
//直接调用辅助方法,返回结果
return(User) EhCacheProvider.getObjectInCache(USER_CACHENAME, sid);
}
public voidsetInCache(String sid, User user) {
//调用辅助方法,放入缓存
EhCacheProvider.setObjectInCache(USER_CACHENAME, sid, user);
}
public voiddelCache() {
//调用辅助方法,清空缓存数据
EhCacheProvider.delCache(USER_CACHENAME);
log.info("清空名称为[" + USER_CACHENAME + "]的缓存");
}
publicboolean checkKey(String sid) {
returnEhCacheProvider.checkKey(USER_CACHENAME, sid);
}
}
4、
public class Controllers extendsActionSupport{
privatestatic final long serialVersionUID = 1L;
@Autowired
privateUserService userService;
private Useruser;
privateIehCacheService<User>userCacheService = new UserCacheService();
privatestatic Log log = LogFactory.getLog(UserControllers.class);
public UsergetUser() {
returnuser;
}
public voidsetUser(User user) {
this.user =user;
}
publicString selectUser(){
//把对象加入缓存
if(!userCacheService.checkKey(String.valueOf(user.getId()))){
userCacheService.setInCache(String.valueOf(user.getId()),user);
log.info(userr.getUsername()+"加入缓存成功。");
}else{
UsercacheUser =userCacheService.getInCache(String.valueOf(user.getId()));
if(cacheUser!=null){
log.info("缓存中已经存在此用户:"+cacheUser.getUsername());
}
log.info(db_user.getUsername()+"加入缓存失败。");
}
}
}
一、准备工作
二、添加spring配置文件applicationContext-cache.xml
<?xml version="1.0"encoding="UTF-8"?>
<beansxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
</beans>
三、添加EhCache配置文件ehcache.xml
<?xml version="1.0"encoding="UTF-8"?>
<ehcache>
</ehcache>
四、测试类
1、EhCacheProvider.java
public class EhCacheProvider {
}
2、IehCacheService.java
public interface IehCacheService<T>{
}
3、CacheService.java
public class CacheService implementsIehCacheService<User> {
}
4、
public class Controllers extendsActionSupport{
}