hibernate的二级缓存

前言

今天为大家分享的知识点是hibernate中的二级缓存啦~

1、缓存的用处

它可以提高程序的性能

2、缓存的应用以及场景

2.1、 很少被修改或根本不改的数据

2.2、 字典数据

例如:小汽车专卖店的固定型号数据或者我们每个人的身份证号都是未曾修改过的,所以说这是缓存!

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

3、ehcache的概念

Ehcache 是现在最流行的纯Java开源缓存框架,配置简单、结构清晰、功能强大

开源:指的是源代码免费开放,可进行二次开发!

注意:2.X版本和3.X相比而言,3.x的版本和2.x的版本API差异比较大

Redis处理的是分布式缓存!

4、ehcache的特点

4.1 够快

Ehcache终被设计于large,high concurrency systems.

4.2 够简单

开发者提供的接口简单明了,
从Ehcache的搭建到运用运行仅仅需要几分钟,
Ehcache被广泛的运用于其他的开源项目

4.3 够袖珍

  一般Ehcache的发布版本不会到2M

4.4 够轻量

  核心程序仅仅依赖slf4j这一个包,没有之一!

4.5 好扩展

 Ehcache提供了对大数据的内存和硬盘的存储,
 最近版本允许多实例、保存对象高灵活性、
 提供LRU、LFU、FIFO淘汰算法,
 基础属性支持热配置、支持的插件多

4.6 监听器

 缓存管理器监听器 (CacheManagerListener)
 和 缓存监听器(CacheEvenListener),
 做一些统计或数据一致性广播挺好用的

4.7 分布式缓存

 从Ehcache 1.2开始,支持高性能的分布式缓存,
 兼具灵活性和扩展性

5、一级缓存与二级缓存

1、一级缓存(session)

2、二级缓存(sessionFactory)

6、 cacheManager的使用

CacheManager:缓存管理器
Cache:缓存对象,缓存管理器内可以放置若干cache,存放数据的实质,所有cache都实现了Ehcache接口
Element:单条缓存数据的组成单位

顺序层次:ehcache.xml->CacheManager->Cache->Element(javabean),缓存对象及其属性都可序列化 。

Ehcache二级缓存的配置

1、导入相关依赖

pom.xml文件

当然这些需要导入的jar包依赖代码不需手写,只需去添maven的中央仓库中复制代码即可~

<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.wangqiuping</groupId>
  <artifactId>Cache</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>hibrenate Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <!--相关依赖版本的配置-->
  <properties>
  	<servlet.version>4.0.1</servlet.version>
  	<junit.version>3.8.1</junit.version>
  	<MySQL.version>5.1.44</MySQL.version>
  	<jstl.version>1.2</jstl.version>
  	<hibernate.version>5.2.12.Final</hibernate.version>
  	<ehcache.version>2.10.0</ehcache.version>
  </properties>
  
<dependencies>
<!-- servlet依赖 -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>${servlet.version}</version>
    <scope>provided</scope>
</dependency>  	
  	
<!-- junit依赖 -->
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>${junit.version}</version>
    <scope>test</scope>
  </dependency>
  
  <!-- MySQL依赖 -->
  <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${MySQL.version}</version>
</dependency>

 <!-- jstl依赖-->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>${jstl.version}</version>
</dependency>

<!-- taglibs依赖-->
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

<!-- tomcat依赖 -->
<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-jsp-api</artifactId>
    <version>8.5.56</version>
</dependency>

<!--hibernate依赖-->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>${hibernate.version}</version>
</dependency>

<!--ehcache依赖-->
<dependency>
    	<groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache</artifactId>
      <version>${ehcache.version}</version>
    </dependency>
<!-- ehcache与hibernate的桥接包 -->
 <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-ehcache</artifactId>
     <version>5.2.12.Final</version>
   </dependency>
    
<!-- log配置:Log4j2 + Slf4j -->
<!-- slf4j核心包 -->
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-api</artifactId>
	<version>1.7.7</version>
</dependency>

<!-- slf4j相关依赖-->
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>jcl-over-slf4j</artifactId>
	<version>1.7.7</version>
	<scope>runtime</scope>
</dependency>

<!--用于与slf4j保持桥接 -->
<dependency>
	<groupId>org.apache.logging.log4j</groupId>
	<artifactId>log4j-slf4j-impl</artifactId>
	<version>2.9.1</version>
</dependency>

<!--核心log4j2jar包 -->
<dependency>
	<groupId>org.apache.logging.log4j</groupId>
	<artifactId>log4j-api</artifactId>
	<version>2.9.1</version>
</dependency>

<!--核心log4j2j相关依赖 -->
<dependency>
	<groupId>org.apache.logging.log4j</groupId>
	<artifactId>log4j-core</artifactId>
	<version>2.9.1</version>
</dependency>

<!--web工程需要包含log4j-web,非web工程不需要 -->
<dependency>
	<groupId>org.apache.logging.log4j</groupId>
	<artifactId>log4j-web</artifactId>
	<version>2.9.1</version>
	<scope>runtime</scope>
</dependency>

<!--需要使用log4j2的AsyncLogger需要包含disruptor -->
<dependency>
	<groupId>com.lmax</groupId>
	<artifactId>disruptor</artifactId>
	<version>3.2.0</version>
</dependency>
  
</dependencies>
<build>
  <finalName>Cache</finalName>
  <plugins>
  	<plugin>
	<groupId>org.apache.maven.plugins</groupId>
	<artifactId>maven-compiler-plugin</artifactId>
	<version>3.7.0</version>
	<configuration>
		<source>1.8</source>
		<target>1.8</target>
		<encoding>UTF-8</encoding>
	</configuration>
</plugin>
  </plugins>
</build>
</project>

具体操作如下:
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

2、添加ehcache.xml到resources目录下

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">
         
 <diskStore path="java.io.tmpdir"/>

 <defaultCache eternal="false"   
   maxElementsInMemory="1000" 
   overflowToDisk="false" 
   diskPersistent="false" 
   timeToIdleSeconds="0" 
   timeToLiveSeconds="600" 
   memoryStoreEvictionPolicy="LRU"/>
                      
  <cache name="bookCache"  eternal="false" 
       maxElementsInMemory="100"
       overflowToDisk="false" 
       diskPersistent="false" 
       timeToIdleSeconds="0"
       timeToLiveSeconds="300" 
       memoryStoreEvictionPolicy="LRU"/>
</ehcache>

ehcache.xml相关解释:

diskStore:指的是磁盘存储(将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存)

defaultCache:默认的管理策略

属性名称相关解释
path指定在硬盘上存储对象的路径
java.io.tmpdir默认的临时文件路径
eternal设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断
maxElementsInMemory在内存中缓存的element的最大数目
overflowToDisk如果内存中数据超过内存限制,是否要缓存到磁盘上
diskPersistent是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false
timeToIdleSeconds对象空闲时间(单位:秒),指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问
imeToLiveSeconds对象存活时间(单位:秒),指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问
memoryStoreEvictionPolicy缓存的3 种清空策略
FIFOfirst in first out (先进先出)
LFU缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存
LRUehcache 默认值,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存)
nameCache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)

3、hibernate.cfg.xml中添加二级缓存配置

主要是从以下几个方面入手(开启二级缓存、开启查询缓存、EhCache驱动)

<!-- 开启二级缓存 -->
    <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>

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!-- 数据库相关配置 -->
		<!-- 链接账户名称 -->
		<property name="connection.username">root</property>
		<!-- 链接账户密码 -->
		<property name="connection.password">123</property>
		<!-- 链接的绝对路径 -->
		<property name="connection.url">
			jdbc:mysql://localhost:3306/t243?useUnicode=true&amp;characterEncoding=UTF-8&amp;userSSL=false
		</property>
		<!-- 驱动的绝对路径 -->
		<property name="connection.driver_class">
			com.mysql.jdbc.Driver
		</property>
		<!-- 数据库方言配置 -->
		<property name="dialect">
			org.hibernate.dialect.MySQLDialect
		</property>
		<!-- 调试相关配置 -->
		<!-- hibernate运行过程是否展示自动生成的SQL代码 -->
		<property name="show_sql">true</property>
		<!-- 是否规范化输出SQL代码 -->
		<property name="format_sql">true</property>
		
		<!-- 开启二级缓存 -->
      	<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>
		
		<!-- 实体映射相关配置 -->
		<mapping resource="com/wangqiuping/entity/Book.hbm.xml"/>
		<mapping resource="com/wangqiuping/entity/Category.hbm.xml"/>
		
	</session-factory>
</hibernate-configuration>

4、指定实体类开启二级缓存

Book

package com.wangqiuping.entity;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
 * 
 * @author 小汪同学
 * 2020年8月3日 下午3:20:44
 */
public class Book implements Serializable {
	
	private Integer bookId;
	private String bookName;
	private Float price;
	Set<Category> categories=new HashSet<Category>();
	
	public Set<Category> getCategories() {
		return categories;
	}
	public void setCategories(Set<Category> categories) {
		this.categories = categories;
	}
	public Integer getBookId() {
		return bookId;
	}
	public void setBookId(Integer bookId) {
		this.bookId = bookId;
	}
	public String getBookName() {
		return bookName;
	}
	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	public Float getPrice() {
		return price;
	}
	public void setPrice(Float price) {
		this.price = price;
	}
	@Override
	public String toString() {
		return "Book [bookId=" + bookId + ", bookName=" + bookName + ", price=" + price + "]";
	}
}

Category

package com.wangqiuping.entity;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
 * 
 * @author 小汪同学
 * 2020年8月3日 下午3:21:10
 */

public class Category implements Serializable {
	
	private Integer categoryId;
	private String categoryName;
	Set<Book> books =new HashSet<Book>();
	
	public Set<Book> getBooks() {
		return books;
	}
	public void setBooks(Set<Book> books) {
		this.books = books;
	}
	public Integer getCategoryId() {
		return categoryId;
	}
	public void setCategoryId(Integer categoryId) {
		this.categoryId = categoryId;
	}
	public String getCategoryName() {
		return categoryName;
	}
	public void setCategoryName(String categoryName) {
		this.categoryName = categoryName;
	}
	@Override
	public String toString() {
		return "Category [categoryId=" + categoryId + ", categoryName=" + categoryName + ", books=" + books + "]";
	}
}

usage:缓存模式
region:定义缓存对象的名称Cache

<cache usage="read-only" region="com.wangqiuping.entity.Book"/>

Book.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.wangqiuping.entity.Book" table="t_book_hb">
	
		 <cache usage="read-only" region="com.wangqiuping.entity.Book"/>	
		
		<id name="bookId" type="java.lang.Integer" column="book_id">
			<generator class="increment"></generator>
		</id>
		<property name="bookName" type="java.lang.String" column="book_name"/>
		<property name="price" type="java.lang.Float" column="price"/>
		<!-- 多对多映射关系 -->
		<!-- 
			name:一方包含多方的属性对象名称,指向多方
			cascade:级联操作 save-update/none/delete/all=delete+save-update
			inverse:是否是主控方, false表示对方不是主控方
							  true表示对方是主控方,由对方来维护中间表
		 	table:表示中间表的名称
		 -->
		<set name="categories" 
		 	 cascade="save-update"
		 	 inverse="false"
		 	 table="t_book_category_hb">
		 	 <!-- 
		 	 	column:指向己方在中间表中的外键字段
		 	  -->
			<key column="bid"></key>
			<!-- 
				class:对方实例完整路径
				column:对方在中间表中的外键字段
			 -->
			<many-to-many class="com.wangqiuping.entity.Category"
						  column="cid">
			</many-to-many>
		</set>
	</class>
</hibernate-mapping>

5、BookDao以及junit测试代码

BookDao

package com.wangqiuping.dao;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.wangqiuping.entity.Book;
import com.wangqiuping.util.SessionFactoryUtils;
/**
 * 
 * @author 小汪同学
 * 2020年8月3日 下午3:27:52
 */

public class BookDao {

	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.wangqiuping.entity.Book");// 指定缓存策略,名字必须实体类的完整类名
		 query.setCacheable(true);// 手动开启二级缓存
		 List<Book> list = query.list();
		 ts.commit();
		 SessionFactoryUtils.closeSession();
		 return list;
	}
}

这里注意两点:
1、指定缓存策略,名字必须是实体类的完整类名
query.setCacheRegion(“com.wangqiuping.entity.Book”)
2、手动开启二级缓存
query.setCacheable(true);

junit测试代码

package com.wangqiuping.dao;

import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.wangqiuping.entity.Book;
/**
 * 
 * @author 小汪同学
 * 2020年8月3日 下午3:53:35
 */
public class BookDaoTest {

	Book  book=null;
	BookDao  bookDao=new BookDao();
	
	
	@Before
	public void setUp() throws Exception {
	  book=new Book();
	}
    //查询单个
	@Test
	public void test() {
		book.setBookId(1);
		Book b1 = bookDao.get(book);
		System.out.println(b1);
		System.out.println("-------------------------------------");
		Book b2 = bookDao.get(book);
		System.out.println(b2);
	}
	
	//查询全部
	@Test
	public void testAll() {
		List<Book> list = bookDao.list();
		list.forEach(b->{
			System.out.println(b);
		});
		System.out.println("-------------------------------------");
		List<Book> lst = bookDao.list();
		lst.forEach(b->{
			System.out.println(b);
		});
	}
}

6、工具类

EhcacheUtil

package com.wangqiuping.util;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import java.io.InputStream;

/**
 * Ehcache工具类
 * @author 小汪同学
 * 2020年8月3日 下午4:03:20
 */
public class EhcacheUtil {

//定义的cachManager缓存管理器,用于存储Cache缓存对象
    private static CacheManager cacheManager;

    static {
        try {
        	//加载根路径下的ehcache.xml并转换为输入流
            InputStream is=EhcacheUtil.class.getResourceAsStream("/ehcache.xml");
            
            cacheManager = CacheManager.create(is);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private EhcacheUtil() {
    }
    /**
     * 往缓存管理器CachManager中指定存储对象Cache中存储数据
     * @param cacheName 缓存对象名
     * @param key		缓存元素名称
     * @param value	 	缓存元素的值
     */
    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);
        }
        //创建一个Element缓存元素,并将缓存元素添加到Cache缓存对象中
        cache.put(new Element(key, value));
    }

    /**
     * 根据缓存对象名获取缓存对象
     * @param cacheName 缓存对象名
     * @param key		缓存元素名称
     * @return
     */
    public static Object get(String cacheName, Object key) {
    	//根据缓存对象名获取缓存管理器中的指定缓存对象
    	Cache cache = cacheManager.getCache(cacheName);
        //根据缓存元素名称获取Cache缓存对象中存储的Element缓存元素
    	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);
    }
}

SessionFactoryUtils

package com.wangqiuping.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
 * 
 * @author 小汪同学
 * 2020年8月3日 下午4:08:11
 */
public class SessionFactoryUtils {

	private static final String 
			HIBERNATE_CONFIG_FILE="hibernate.cfg.xml";
	
	private static ThreadLocal<Session> threadLocal=
			new ThreadLocal<Session>();
	
	//创建数据库的会话工厂
	private static SessionFactory sessionFactory;
	
	//读取hibernate核心配置
	private static Configuration configuration;
	
	static {
		try {
			configuration=new Configuration();
			configuration.configure(HIBERNATE_CONFIG_FILE);
			//创建Session会话工厂
			sessionFactory=configuration.buildSessionFactory();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Session openSession() {
		Session session = threadLocal.get();
		if(null==session) {
			session=sessionFactory.openSession();
			threadLocal.set(session);
		}
		return session;
	}
	
	public static void closeSession() {
		Session session = threadLocal.get();
		if(null!=session) {
			if(session.isOpen())
				session.close();
			threadLocal.set(null);
		}
	}
	
	public static void main(String[] args) {
		Session session = SessionFactoryUtils.openSession();
		System.out.println("Session状态:"+session.isOpen());
		System.out.println("Session会话已打开");
		SessionFactoryUtils.closeSession();
		System.out.println("Session会话已关闭");
	}
}

实现效果

查询单个
在这里插入图片描述
查询全部

首先进行一次查询数据
在这里插入图片描述
进行了一次查询,遍历了两次数据

第一次的数据是从数据库中获取,第二次数据从缓存中获取,因为只进行了一次查询的操作!
在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值