一,使用场景
EHCache是一个非常轻量级的缓冲,是Hibernate的默认缓存。同时ehcache应该说是java范围内使用最广泛的缓存。同时它也支持分布式缓存。也提供了磁盘,内存的缓存存储。
二,使用实例
第1步,需要在项目src下编写ehcache.xml文件
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="C:/ehcache"/>
<cache
name="categoryCache"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
/>
<!--
默认缓存配置,
以下属性是必须的:
name :cache的标识符,在一个CacheManager中必须唯一。
maxElementsInMemory : 在内存中缓存的element的最大数目。
maxElementsOnDisk : 在磁盘上缓存的element的最大数目。
eternal : 设定缓存的elements是否有有效期。如果为true,timeouts属性被忽略。
overflowToDisk : 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上。
以下属性是可选的:
timeToIdleSeconds : 缓存element在过期前的空闲时间。
timeToLiveSeconds : 缓存element的有效生命期。
diskPersistent : 在VM重启的时候是否持久化磁盘缓存,默认是false。
diskExpiryThreadIntervalSeconds : 磁盘缓存的清理线程运行间隔,默认是120秒.
memoryStoreEvictionPolicy : 当内存缓存达到最大,有新的element加入的时候,
移除缓存中element的策略。默认是LRU,可选的有LFU和FIFO
-->
</ehcache>
第2步,导入jar包
第3步,在Category的实现类中使用ehcache
package com.itheima.service.impl;
import com.itheima.dao.CategoryDao;
import com.itheima.dao.impl.CategoryDaoImpl;
import com.itheima.domain.Category;
import com.itheima.service.CategoryService;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import java.io.InputStream;
import java.util.List;
public class CategoryServiceImpl implements CategoryService {
/**
* 查询所的有分类
*
* @return
* @throws Exception
*/
@Override
public List<Category> findAll() throws Exception {
//1,创建缓存管理器
CacheManager cm = CacheManager.create(CategoryServiceImpl.class.getClassLoader().getResourceAsStream("ehcache.xml"));
//2,获取指定的缓存
Cache cache = cm.getCache("categoryCache");
//3,通过缓存获取数据 将cache看成一个map即可
Element element = cache.get("clist");
List<Category> list = null;
//4,判断数据
if (element == null) {
//从数据库中获取
CategoryDao cd = new CategoryDaoImpl();
list = cd.findAll();
//将list放入缓存
cache.put(new Element("clist", list));
System.out.println("缓存中没有数据,已去数据库中获取");
} else {
//直接返回
list = (List<Category>) element.getObjectValue();
System.out.println("缓存中有数据");
}
return list;
}
public static void main(String[] args) {
InputStream is = CategoryServiceImpl.class.getClassLoader().getResourceAsStream("ehcache.xml");
System.out.println(is);
}
}
第4步
运行程序,查看控制台是否有输出(注意:需要在Category实体中实现Serializable,否则会报错,public class Category implements Serializable )
成功