hibernate-没用的ehcache(二级缓存)

1. 为什么需要缓存
提高程序的性能
2. 什么样的数据需要缓存
很少被修改或根本不改的热数据

热数据:已上架商品/已下架商品

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

3. ehcache是什么

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

注1:本章介绍的是2.X版本,3.x的版本和2.x的版本API差异比较大

4. 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开始,支持高性能的分布式缓存,兼具灵活性和扩展性
5. ehcache的使用
5.1 导入相关依赖
  <dependency>
  	<groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.10.0</version>
  </dependency>

注释: 通过properties全局变量

2.10.0

${ehcache-version}
在这里插入图片描述

5.2 resources:ehcache.xml

在这里插入图片描述
注释: 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"/>


<!--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>

数据已过期

##编码

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

在这里插入图片描述
在这里插入图片描述
EhcacheUtil源码:

package com.zking.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;//cache缓存manager管理器
//执行一次
static {
    try {
        InputStream is = EhcacheUtil.class.getResourceAsStream("/ehcache.xml");//去项目里面读取/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);
    }
    //把要保存的key,value--new成一个Element如何让cache缓存对象保存到put里面
    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包含两个部分一个key一个value
    Element element = cache.get(key);
    //如果element为空返回null不为空返回value
    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);
}
}

重点:
在这里插入图片描述

<!--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 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存-->
##timeToIdleSeconds:多少分钟刷新一次;
timeToLiveSeconds:存活多少分钟;
5.4 缓存对象及其属性都要序列化
  1)属性通常使用的:implements Comparable<Integer>
  2)对象通常使用的:implements Serializable
ehcache流程图:

在这里插入图片描述

6. hibernate缓存
6.1 一级缓存
  session

在这里插入图片描述
BookDAOTest源码:

  package com.zking.test.Dao;

import static org.junit.Assert.*;

import org.junit.Test;

import com.zking.test.Model.BookModel;
import com.zking.test.Util.EhcacheUtil;

public class BookDaoTest {

private BookDao bookDAO = new BookDao();
/**
 * 通过此案例,让大家体会缓存的一个好处
 * 
 * @param bookId
 * @return
 */
public BookModel findById(Integer bookId) {// 开启缓存功能
	// 缓存找-->数据库找
	BookModel b = (BookModel) EhcacheUtil.get("book", bookId);
	if (null == b) {
		BookModel book = new BookModel();
		book.setBookId(bookId);
		b = bookDAO.loat(book);
		if (null != b) {
			EhcacheUtil.put("book", b.getBookId(), b);
		}
	}
	return b;
}

@Test
public void test1() {
	//第一次进来缓存为空去数据库查询出了结果
	System.out.println("aaaaaaaaaaaaa");
	BookModel b = findById(1);
	System.out.println(b);
	System.out.println("bbbbbbbbbbbbbb");
	//缓存里已有数据不需要去数据库查询
	BookModel b2 = findById(1);
	System.out.println(b2);
}

@Test
public void test2() {
	//拿到系统的一个临时文件路径
	System.out.println(System.getProperty("java.io.tmpdir"));
}

}
6.2 二级缓存
  SessionFactory
  可拔插式
7. hibernate(5.2.12.Final)中使用二级缓存步骤(ehcache)
7.1 导入ehcache相关依赖
  <dependency>
     <groupId>org.hibernate</groupId>
     <artifactId>hibernate-ehcache</artifactId>
    <version>5.2.12.Final</version>
  </dependency>
7.2 resources添加ehcache.xml
7.3 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>
7.4 指定实体类开启二级缓存
  <!-- 注解式开发 -->
  <class-cache usage="read-write" class="entity.Dict"/>

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

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

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

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

参考源码

BookDao源码:

package com.zking.test.Dao;

import java.util.ArrayList;
import java.util.List;


import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import com.zking.test.Model.BookModel;
import com.zking.test.Util.SessionFactoryUtil;

public class BookDao {
	
public BookModel loat(BookModel book) {
	Session session = null;
	Transaction transaction =null;
	try {
		session = SessionFactoryUtil.openSession();//创建会话
		transaction = session.beginTransaction();//打开事务
		BookModel b = session.get(BookModel.class, book.getBookId());
		transaction.commit();
		return b;
	} catch (Exception e) {
		if(null !=transaction) {
			transaction.rollback();
		}
		throw new RuntimeException(e);
	}finally {
		SessionFactoryUtil.closeSession();
	}
}

public List<BookModel> list1() {
	String hql = "select b from BookModel b";
	List<BookModel> list = new ArrayList<BookModel>();

	Session session = null;
	Transaction transaction = null;
	try {
		session = SessionFactoryUtil.openSession();
		transaction = session.beginTransaction();
		Query query = session.createQuery(hql);
		// 手动指定缓存策略(可选)
		query.setCacheRegion("com.zking.test.Model.BookModel");// 指定缓存策略,名字必须实体类的完整类名
		// 手动开启二级缓存
		query.setCacheable(true);// 手动开启二级缓存
		list = query.list();
		transaction.commit();// 提交事务
		return list;
	} catch (Exception e) {
		if (null != transaction) {
			transaction.rollback();// 回滚事务
		}
		throw new RuntimeException(e);
	} finally {
		SessionFactoryUtil.closeSession();
	}
}

}

BookDaoTest源码:
package com.zking.test.Dao;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.Before;
import org.junit.Test;

import com.zking.test.Model.BookModel;

public class BookDaoTest {

private BookDao bookDAO = new BookDao();

private BookModel book;

@Before
public void before() {
	book = new BookModel();
}
/**
 * 现在的用法
 * 二级缓存
 */
@Test
public void loat() {
	book.setBookId(1);
	BookModel b = bookDAO.loat(book);
	System.out.println(b);
	System.out.println("xxxxxxxxxxxxxxxxxxxx");
	BookModel b2 = bookDAO.loat(book);
	System.out.println(b2);
}

@Test
public void list1() {
	List<BookModel> list1 = bookDAO.list1();
	for (BookModel b : list1) {
		System.out.println(b);
	}
	System.out.println("xxxxxxxxxxxxxxxxxxxxx");
	List<BookModel> list2 = bookDAO.list1();
	for (BookModel b : list2) {
		System.out.println(b);
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值