Hibernate之二级缓存

二级缓存简介:

Hibernate的二级缓存由SessionFactory对象管理,是应用级别的缓存。它可以缓存整个应用的持久化对象,所以又称为“SessionFactory缓存”。
hibernate二级缓存中的缓存对象可以被整个应用的Session对象共享,即使关闭当前Session对象,新建的Session对象仍可使用。使用Hibernate的二级缓存之后查询数据,Session对象会首先在以及缓存中查找有无缓存数据被命中。如果没有,则查找二级缓存。如果有,则直接返回所命中的数据;否则查询数据库。

二级缓存的作用:

使用缓存,是需要对应用系统进行性能优化而常采用的一种重要手段。合理地运用缓存,可以极大的提高应用系统的运行效率。
Hibernate中应用缓存:因为应用程序访问数据库,读写数据的代价非常高,而利用持久层的缓存可以减少应用程序与数据库之间的交互,即把访问过的数据保存到缓存中,应用程序再次访问已经访问过的数据,这些数据就可以从缓存中获取,而不必再从数据库中获取。同时如果数据库中的数据被修改或者删除,那么是、该数据所对应的缓存数据,也会被同步修改或删除,进而保持缓存数据的一致性。

什么样的数据需要二级缓存:
很少被修改或根本不改的数据 权限

业务场景比如:耗时较高的统计分析sql、电话账单查询sql等

ehcache是什么

Ehcache 是现在最流行的纯Java开源缓存框架,配置简单、结构清晰、功能强大,ehcache可以很好的和hibernate继承。作为hibernate的二级缓存使用。

ehcache的特点

1 够快
Ehcache的发行有一段时长了,经过几年的努力和不计其数的性能测试,Ehcache终被设计于large, high concurrency systems.
2 够简单
开发者提供的接口非常简单明了,从Ehcache的搭建到运用运行仅仅需要的是你宝贵的几分钟。其实很多开发者都不知道自己用在用Ehcache,Ehcache被广泛的运用于其他的开源项目
3 够袖珍
关于这点的特性,官方给了一个很可爱的名字small foot print ,一般Ehcache的发布版本不会到2M,V 2.2.3 才 668KB。
4 够轻量
核心程序仅仅依赖slf4j这一个包,没有之一!
5 好扩展
Ehcache提供了对大数据的内存和硬盘的存储,最近版本允许多实例、保存对象高灵活性、提供LRU、LFU、FIFO淘汰算法,基础属性支持热配置、支持的插件多
6 监听器
缓存管理器监听器 (CacheManagerListener)和 缓存监听器(CacheEvenListener),做一些统计或数据一致性广播挺好用的
7 分布式缓存
从Ehcache 1.2开始,支持高性能的分布式缓存,兼具灵活性和扩展性

看图理解理解ehcache的缓存:如下图:
在这里插入图片描述
利用map集合简易实现缓存原理:

package com.LHJ.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);
		if(value == null) {
			System.out.println("请求数据库...         第一步");
			cache.put(key, new String[] {"LHJ"});
			
			System.out.println("数据库查出结果集放入缓存...         第二步");
			System.out.println("从缓存中读取数据...         第三步");
			return cache.get(key);
		}else {
			System.out.println("从缓存中读取数据...         第4/5/6步");
		}
		return value;
	}
	
	public static void main(String[] args) {
		System.out.println(getValue("sname"));
		System.out.println(getValue("sname"));
	}
}

在这里插入图片描述
EhcacheUtil.java
如果我们没有设置它超过最大值溢出部分的存储地方,他会默认的存储到java.io.tmpdir

package com.LHJ.six.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);
    }
}

测试代码:

package com.LHJ.six.test;

import com.LHJ.six.util.EhcacheUtil;

/**
 * 演示利用缓存存储数据
 * @author Administrator
 *
 */
public class EhcacheDemo2 {
	public static void main(String[] args) {
		System.out.println(System.getProperty("java.io.tmpdir"));
		EhcacheUtil.put("com.LHJ.four.entity.Book", 11, "LHJzzzz");
		System.out.println(EhcacheUtil.get("com.LHJ.four.entity.Book", 11));
	}
}

利用ehcache缓存存储数据、读取数据:
首先导入pom依赖:

<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.LHJ</groupId>
  <artifactId>LHJ_hibernate</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>LHJ_hibernate 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>LHJ_hibernate</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:
核心配置文件,关于ehcache的配置都在这里面定义(里面有注解),如果没有这个配置文件那么ehcache就会使用默认的配置。

<?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="D://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.LHJ.one.entity.User" eternal="false" maxElementsInMemory="100"
           overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
           timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
</ehcache>

然后在主配置文件中配置如下代码:
在这里插入图片描述
案例:
在这里插入图片描述
上面只会查一次数据库,不管你导入还是不导入ehcache都一样。上面就是演示一级缓存,一级缓存是session。session是事务范围的缓存。该缓存直接是Hibernate管理。

在这里插入图片描述
在这里插入图片描述
使用二级缓存后上面的代码只会执行一次查询语句
开启二级缓存后,默认查询单个的话是会使用二级缓存的,但是查询多条记录是不会使用二级缓存的;并且在这里需要区分session级别的缓存与sessionfactory级别的缓存。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值