hibernate之二级缓存

1、什么是缓存

缓存是介于应用程序和物理数据源之间,其作用是为了降低应用程序对物理数据源访问的频次,从而提高了应用的运行性能。缓存内的数据是对物理数据源中的数据的复制,应用程序在运行时从缓存读写数据,在特定的时刻或事件会同步缓存和物理数据源的数据。

缓存的介质一般是内存,所以读写速度很快。但如果缓存中存放的数据量非常大时,也会用硬盘作为缓存介质。缓存的实现不仅仅要考虑存储的介质,还要考虑到管理缓存的并发访问和缓存数据的生命周期。

2、为什么需要缓存

拉高程序的性能

3、什么是hibernate的二级缓存

hibernate的二级缓存是SessionFactory级别的缓存, 是一种进程级别的缓存, 这个缓存可以跨session

生命周期跟SessionFactory周期一样, 如果关闭SessionFactory, 则二级缓存消失

hibernate二级缓存跟一级缓存的相同点在于同样只能缓存实体对象而不能缓存属性

4、什么样的数据适合存放到hibernate二级缓存中

  1、很少被修改的数据

  2、不是很重要的数据,允许出现偶尔并发的数据

  3、不会被并发访问的数据

  4、参考数据

5、不适合存放到hibernate二级缓存的数据

  1、经常被修改的数据

  2、财务数据,绝对不允许出现并发

  3、与其他应用共享的数据。

6、第三方的二级缓存产品: ehcache

ehcache 是现在最流行的纯Java开源缓存框架,配置简单、结构清晰、功能强大,支持在内存和硬盘上做存储/支持集群/支持查询缓存。

7、hibernate(5.2.12.Final)中使用二级缓存步骤(ehcache)

a、导入ehcache相关依赖

b、在项目的src目录下添加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="java.io.tmpdir"/> -->
	<diskStore path="D:\"/>

    <!--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="300" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>


    <!--name: Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)-->
    <cache name="stuCache" eternal="false" maxElementsInMemory="100"
           overflowToDisk="true" diskPersistent="false" timeToIdleSeconds="0"
           timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
</ehcache>

c、在hibernate.cfg.xml文件中添加二级缓存相关配置

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

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

      <!-- 注解式开发 -->
      <class-cache usage="read-write" class="entity.Dict"/>

      <!-- xml配置方式 -->
      <class table="t_sys_dict" name="entity.Dict">
		<cache usage="read-write"/> 
                .......
      </class>

 注:查全部需要编写代码来开启二级缓存的
         query.setCacheRegion("entity.Dict");//指定缓存策略,名字必须实体类的完整类名
         query.setCacheable(true);//手动开启二级缓存

        /**
	 * 演示查单个用户使用了缓存
	 * @author LJ
	 * @Date 2018年10月31日
	 * @Time 下午2:23:29
	 */
	@Test
	public void test3() {
		Session session = SessionFactoryUtil.getSession();
		Transaction transaction = session.beginTransaction();
		
		User user1 = session.get(User.class, 1);
		System.out.println(user1);
		User user2 = session.get(User.class, 1);
		System.out.println(user2);
		User user3 = session.get(User.class, 1);
		System.out.println(user3);
		
		transaction.commit();
		SessionFactoryUtil.closeSession();
	}

运行效果:

        /**
	 * hibernate二级缓存不会同时缓存多条数据
	 * @author LJ
	 * @Date 2018年10月31日
	 * @Time 下午2:26:41
	 */
	@Test
	public void test4() {
		Session session = SessionFactoryUtil.getSession();
		Transaction transaction = session.beginTransaction();
		
		Query query = session.createQuery("from User");
		List list = query.list();
		System.out.println(list.size());
		List list2 = query.list();
		System.out.println(list2.size());
		
		transaction.commit();
		SessionFactoryUtil.closeSession();
	}

运行效果:

如果要缓存多条数据,则需手动开启

猜你喜欢

转载自blog.csdn.net/weixin_42687829/article/details/83625546