Hibernate之二级缓存
什么是Hibernate的缓存
Hibernate提供了一级缓存和二级缓存,合理的利用缓存可以有助于提高系统的性能,为了避免不合理的利用缓存导致内存过度消耗降低系统性能,可以通过合理配置缓存的参数来避免这个问题。
缓存的目的是为了通过减少应用程序对物理数据访问的次数来提高程序运行的效率,原理则是把当前或接下来一段时间有可能会用到的数据保存到内存中,在使用时直接从内存中读取,而不是从硬盘上读取,简单说,缓存就是数据库中的数据在内存中的“临时容器”。
一级缓存
Hibernate中的一级缓存由Session管理,二级缓存由SessionFactory来管理。在使用时,二级缓存是可有可无的,但一级缓存是必不可少的。
一级缓存的使用场合:
当使用Session查询数据时,首先会在Session内部查找该对象是否存在,若存在,则直接返回,否则,就到数据库中查询,并将查询到的结果缓存起来以便后期使用。一级缓存的缺点就是当使用Session来表示一次会话时,它的生命周期较短,而且它不是线程安全的,不能被多个线程共享,因此,在实际使用时,对效率的提升不是非常明显。
二级缓存
鉴于以上原因,引入二级缓存的概念。二级缓存用来为Hibernate配置一种全局的缓存,以便实现多个线程与实务共享。在使用了二级缓存机制后,当查询数据时,会首先在内存缓存中查找,如果不存在,接着在二级缓存中查找,最后才去数据库中查找。与一级缓存相比,二级缓存还是独立于Hibernate的软件部件,属于第三方的产品,常见的产品有EhCache、OSCache、JbossCache等。Hibernate3默认使用的产品是EhCache。在使用时,可以根据需求通过配置缓存插件实现二级缓存功能,Hibernate为了集成这些插件,提供了org.hibernate.cache.CacheProvider接口来充当缓存插件与Hibernate之间的适配器。当然,二级缓存除了以内存作为存储介质外,还可以选用硬盘等外部存储设备。
二级缓存适合的几种情况:
数据量较小。(数据量太大会消耗大量内存,造成内存资源紧张,降低系统性能)
对数据的修改较少。(会造成频繁对缓存中的数据进行同步,影响系统的性能)
不会被大量的应用共享的数据。(数据被大量线程或事务共享,多线程访问的同步机制会影响系统性能)
不是很重要的数据。(如果要查询的数据对正确性要求较高,如财务,最好不要使用二级缓存)
为什么需要缓存
拉高程序的性能
介绍一下数据库的类型:
关系型数据库:数据与数据之间存在关系(联系)的数据库 mysql/Oracle、sqlserver
非关系型数据库:数据与数据之间是不存在关系的,key-value
1、基于文件存储的数据库:ehcache
2、基于内存存储的数据库:redis、memcache
3、基于文档存储的数据库:mongodb
2. 什么样的数据需要缓存
很少被修改或根本不改的数据 数据字典
业务场景比如:耗时较高的统计分析sql、电话账单查询sql等
ehcache是什么
Ehcache 是现在最流行的纯Java开源缓存框架,配置简单、结构清晰、功能强大
注1:本章介绍的是2.X版本,3.x的版本和2.x的版本API差异比较大
redis
ehcache的特点
4.1 够快
Ehcache的发行有一段时长了,经过几年的努力和不计其数的性能测试,Ehcache终被设计于large, high concurrency systems.
4.2 够简单
开发者提供的接口非常简单明了,从Ehcache的搭建到运用运行仅仅需要的是你宝贵的几分钟。其实很多开发者都不知道自己用在用Ehcache,Ehcache被广泛的运用于其他的开源项目
4.3 够袖珍
关于这点的特性,官方给了一个很可爱的名字small foot print ,一般Ehcache的发布版本不会到2M,V 2.2.3 才 668KB。
4.4 够轻量
核心程序仅仅依赖slf4j这一个包,没有之一!
4.5 好扩展
Ehcache提供了对大数据的内存和硬盘的存储,最近版本允许多实例、保存对象高灵活性、提供LRU、LFU、FIFO淘汰算法,基础属性支持热配置、支持的插件多
4.6 监听器
缓存管理器监听器 (CacheManagerListener)和 缓存监听器(CacheEvenListener),做一些统计或数据一致性广播挺好用的
4.7 分布式缓存
从Ehcache 1.2开始,支持高性能的分布式缓存,兼具灵活性和扩展性
基础配置文件
pop.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xyx</groupId>
<artifactId>T224_hibernate2</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>T224_hibernate2 Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.version>4.12</junit.version>
<servlet.version>4.0.0</servlet.version>
<hibernate.version>5.2.12.Final</hibernate.version>
<mysql.driver.version>5.1.46</mysql.driver.version>
<ehcache.version>2.10.0</ehcache.version>
<slf4j-api.version>1.7.7</slf4j-api.version>
<log4j-api.version>2.9.1</log4j-api.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.driver.version}</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>${ehcache.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- slf4j核心包 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j-api.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j-api.version}</version>
<scope>runtime</scope>
</dependency>
<!--用于与slf4j保持桥接 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j-api.version}</version>
</dependency>
<!--核心log4j2jar包 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j-api.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j-api.version}</version>
</dependency>
</dependencies>
<build>
<finalName>xyx_hibernate2</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
ehcache.xml
<?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="C://xxx"/>
<!--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="com.xyx.one.entity.User" eternal="false" maxElementsInMemory="100"
overflowToDisk="true" diskPersistent="true" timeToIdleSeconds="0"
timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
</ehcache>
hibernate.cfg.xml
指定hibernate实用的二级缓存
<!-- 开启二级缓存 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 开启查询缓存 -->
<property name="hibernate.cache.use_query_cache">true</property>
<!-- EhCache驱动 -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
util
EhcacheUtil
package com.xyx.six.test.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);
Element element = cache.get(key);
return null == element ? null : element.getValue();
}
public static void remove(String cacheName, Object key) {
Cache cache = cacheManager.getCache(cacheName);
cache.remove(key);
}
}
test
EhcacheDemo1
package com.xyx.six.test;
import java.util.HashMap;
import java.util.Map;
/**
* 利用map集合简易实现缓存原理
* @author Administrator
*
*/
public class EhcacheDemo1 {
static Map<String, Object> cache = new HashMap<String, Object>();
static Object getValue(String key) {
Object value = cache.get(key);
System.out.println("从缓存中获取数据。。。。");
if(value == null) {
System.out.println("从软降想对应的配置文件(数据库)中获取数据。。。。");
cache.put(key, new String[] {"zs"});
return cache.get(key);
}
return value;
}
public static void main(String[] args) {
System.out.println(getValue("sname"));
System.out.println(getValue("sname"));
}
//输出结果从缓存中获取数据。。。。
// 从软降想对应的配置文件(数据库)中获取数据。。。。
// [Ljava.lang.String;@7852e922 zs
// 从缓存中获取数据。。。。
// [Ljava.lang.String;@7852e922 zs
}
EhcacheDemo2
package com.xyx.six.test;
import com.xyx.six.test.util.EhcacheUtil;
/**
* 演示利用缓存存储数据
* @author Administrator
*
*/
public class EhcacheDemo2 {
public static void main(String[] args) {
//log4j2异步
System.out.println(System.getProperty("java.io.tmpdir"));
EhcacheUtil.put("com.xyx.one.entity.User", 11, "zhangsan");
System.out.println(EhcacheUtil.get("com.xyx.one.entity.User", 11));
}
}
EhcacheDemo3
package com.xyx.six.test;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.xyx.four.dao.SessionFactoryUtils;
import com.xyx.one.dao.UserDao;
import com.xyx.one.entity.User;
/**
* 演示查单个用户使用了缓存
* @author Administrator
*
*/
public class EhcacheDemo3 {
/**
* 默认情况下,sql语句形成了三次,这里为了提高性能,必须使用二级缓存SessionFactory缓存
* <!-- 开启二级缓存 -->
* <property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 开启查询缓存 -->
<property name="hibernate.cache.use_query_cache">true</property>
<!-- EhCache驱动 -->
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
映射文件中添加标签
<cache usage="read-write" region="com.javaxl.one.entity.User"/>
这里的region指的是Ehcache.xml中cacheName
* @param args
*/
public static void main(String[] args) {
UserDao userDao = new UserDao();
User u = new User();
u.setId(1);
User user = userDao.get(u);
System.out.println(user);
User user2 = userDao.get(u);
System.out.println(user2);
User user3 = userDao.get(u);
System.out.println(user3);
// test1();
}
/**
* 同一个session,sql语句只生成一次,这里用到了一级缓存
* session级别的缓存就是一级缓存
* sessionfactory级别的缓存是二级缓存
* 默认一级缓存是开启的,二级缓存不开启
*/
public static void test1() {
Session session = SessionFactoryUtils.openSession();
Transaction transaction = session.beginTransaction();
User user = session.get(User.class, 7);
System.out.println(user);
User user2 = session.get(User.class, 7);
System.out.println(user2);
User user3 = session.get(User.class, 7);
System.out.println(user3);
transaction.commit();
session.close();
}
}
EhcacheDemo4
package com.xyx.six.test;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import com.xyx.four.dao.SessionFactoryUtils;
/**
* hibernate二级缓存不会同时缓存多条数据
* 默认会对查询出的单条记录使用缓存机制
* 并不会对查询出的多条记录使用二级缓存机制
* 查询出多条记录的时候,想使用二级缓存的话,还需要通过代码去开启
* query.setCacheable(true);
*
* hibernate针对单挑数据和多条数据使用二级缓存为什么差异性呢?
* @author Administrator
*
*/
public class EhcacheDemo4 {
public static void main(String[] args) {
Session session = SessionFactoryUtils.openSession();
Transaction transaction = session.beginTransaction();
Query query = session.createQuery("from User");
query.setCacheable(true);
List list = query.list();
System.out.println(list);
List list2 = query.list();
System.out.println(list2);
List list3 = query.list();
System.out.println(list3);
transaction.commit();
session.close();
}
}
没有加 query.setCacheable(true); 相当于一星
会运行3次比较繁琐
加了 query.setCacheable(true);只运行一次,降低了代码量,提高了效率