前言
缓存的使用能让我们更好的优化程序的性能,一般的话是操作很少被修改或根本不改的数据,我们可以通过合理配置缓存参数来高效的提高我们程序的性能。
ehcache是什么?
Ehcache 是纯Java开源缓存框架,配置简单、结构清晰、功能强大本章介绍的是2.X版本,3.x的版本和2.x的版本API差异比较大。
ehcache的特点
够快、够简单、够袖珍、够轻量、好扩展、提供缓存管理器监听器、支持分布式缓存。
cacheManager的使用
CacheManager:缓存管理器
Cache:缓存对象,缓存管理器内可以放置若干cache,存放数据的实质,所有cache都实现了Ehcache接口
Element:单条缓存数据的组成单位
顺序层次:ehcache.xml->CacheManager->Cache->Element(javabean),缓存对象及其属性都可序列化 。
ehcache的使用
1.导入ehcache的依赖
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.0</version>
</dependency>
2.使用二级缓存
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.2.12.Final</version>
</dependency>
3.配置缓存文件参数
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<!--磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存-->
<!--path:指定在硬盘上存储对象的路径-->
<!--java.io.tmpdir 是默认的临时文件路径。 可以通过如下方式打印出具体的文件路径 System.out.println(System.getProperty("java.io.tmpdir"));-->
<diskStore path="java.io.tmpdir"/>
<!--defaultCache:默认的管理策略-->
<!--eternal:设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断-->
<!--maxElementsInMemory:在内存中缓存的element的最大数目-->
<!--overflowToDisk:如果内存中数据超过内存限制,是否要缓存到磁盘上-->
<!--diskPersistent:是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false-->
<!--timeToIdleSeconds:对象空闲时间(单位:秒),指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问-->
<!--timeToLiveSeconds:对象存活时间(单位:秒),指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问-->
<!--memoryStoreEvictionPolicy:缓存的3 种清空策略-->
<!--FIFO:first in first out (先进先出)-->
<!--LFU:Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存-->
<!--LRU:Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存-->
<defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>
<!--name: Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)-->
<cache name="stuCache" eternal="false" maxElementsInMemory="100"
overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
</ehcache>
EhcacheUtil
package com.liyingdong.util;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import java.io.InputStream;
public class EhcacheUtil {
//缓存管理者
private static CacheManager cacheManager;
static {
try {
InputStream is = EhcacheUtil.class.getResourceAsStream("/ehcache.xml");
cacheManager = CacheManager.create(is);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private EhcacheUtil() {
}
public static void put(String cacheName, Object key, Object value) {
//缓存
Cache cache = cacheManager.getCache(cacheName);
if (null == cache) {
//以默认配置添加一个名叫cacheName的Cache
cacheManager.addCache(cacheName);
cache = cacheManager.getCache(cacheName);
}
//增加元素
cache.put(new Element(key, value));
}
public static Object get(String cacheName, Object key) {
Cache cache = cacheManager.getCache(cacheName);
if (null == cache) {
return null;
}
Element element = cache.get(key);
return null == element ? null : element.getValue();
}
public static void remove(String cacheName, Object key) {
Cache cache = cacheManager.getCache(cacheName);
if (null == cache) {
return;
}
cache.remove(key);
}
}
hibernate.cfg.xml中添加二级缓存相关配置
放入位置在调试配置后面。
<!-- 开启二级缓存 -->
<!-- 对查单个生效,对query.list()方法不生效-->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 开启查询缓存 query.list()-->
<property name="hibernate.cache.use_query_cache">true</property>
<!-- EhCache驱动:连接hibernate与ehcache -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
然后在你指定的实体映射文件中开启二级缓存,比如我这里是开启了book的二级缓存(book.hbm.xml)
<cache usage="read-only" region="com.liyingdong.entity.Book"/>
BookDao
注1:查全部需要编写代码来开启二级缓存的
query.setCacheRegion(“com.zking.entity.User”);// 指定缓存策略,名字必须实体类的完整类名
query.setCacheable(true);// 手动开启二级缓存
public Book get(Book book) {
Session session = SessionFactoryUtils.openSession();
Transaction ts = session.beginTransaction();
//CRUD
Book b = session.get(Book.class, book.getBookId());
ts.commit();
SessionFactoryUtils.closeSession();
return b;
}
public List<Book> list() {
Session session = SessionFactoryUtils.openSession();
Transaction ts = session.beginTransaction();
//CRUD
Query query = session.createQuery(" from Book ");
query.setCacheRegion("com.zking.entity.User");// 指定缓存策略,名字必须实体类的完整类名
query.setCacheable(true);// 手动开启二级缓存
List<Book> list = query.list();
ts.commit();
SessionFactoryUtils.closeSession();
return list;
}
Juint测试
package com.liyingdong.test;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.liyingdong.dao.BookDao;
import com.liyingdong.entity.Book;
public class BookEhcacheTest {
Book book=null;
BookDao bd=new BookDao();
@Before
public void setUp() throws Exception {
book = new Book();
}
//查询单个
@Test
public void test() {
//从数据库查询
book.setBookId(1);
Book b = bd.get(book);
System.out.println(b);
System.out.println("-----------");
//从缓存里面获取
b = bd.get(book);
System.out.println(b);
}
//查询全部
@Test
public void test2() {
//从数据库查询
List<Book> list = bd.list();
System.out.println(list.size());
System.out.println("--------------");
list = bd.list();
System.out.println(list.size());
}
}
效果:
查询单个测试
很明显它的查询语句就执行了一次,而你第二次是获取到缓存中的数据没有进行查询。
查询全部
由于数据比较多不好显示我打印的是size,同样它第二次的值是从缓存中获取的。