Hibernate之二级缓存

一、为什么需要缓存?

拉高程序性能

二、关系型数据库与非关系型数据库

关系型数据库:数据与数据之间存在关系的数据库mysql/Oracle、sqlserver
非关系型数据库:数据与数据之间是不存在关系的,key-value

非关系型数据库分类:
1、基于文件存储的数据库:ehcache
2、基于内存存储的数据库:redis、memcache
3、基于文档存储的数据库:mongodb

三,什么样的数据需要缓存


1、很少被修改的数据
2、不是很重要的数据,允许出现偶尔并发的数据
3、不会被并发访问的数据
4、参考数据,指的是供应用参考的常量数据,它的实例数目有限,它的实例会被许多其他类的实例引用,实例极少或者从来不会被修改

什么样的数据不适合存放到第二级缓存中

1、经常被修改的数据
2、财务数据,绝对不允许出现并发
3、与其他应用共享的数据

四,数据字典


一个项目中所有的基础数据,就是项目中所有的下拉框

解决的问题:如果有一百个下拉框,那么就要建一百个表,数据缓存省略了大量表的创建

表设计:

        数据源表:数据源标识,数据源描述

        数据项表:数据源标识,数据项键,数据值键
 

五、ehcache存储数据

1、导入jar包依赖

pom.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.DHM</groupId>
  <artifactId>hibernate</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>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>8.0.19</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>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>

2、利用map集合简易实现缓存原理

 怎么使用缓存
  1、优先从缓存中获取对应数据
  2、如果获取到了,那么直接返回
  3、没有获取到,那么查询数据库,将数据库对应的数据放入缓存,再返回

 

 EhcacheDemo1 

package com.dhm.text;

import java.util.HashMap;
import java.util.Map;

/**
 * 利用map集合简易实现缓存原理
 * 怎么使用缓存
 * 1、优先从缓存中获取对应数据
 * 2、如果获取到了,那么直接返回
 * 3、没有获取到,那么查询数据库,将数据库对应的数据放入缓存,再返回
 * @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("hello zs");//从数据库读取数据
			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"));
	}
}

运行结果:
          输出值:
         hello zs——从数据库中读取数据
        zs——数据库中得到的
         zs——缓存中得到的

六、ehcache的使用

ehcache的三个核心接口:

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

槽的配置文件ehcache.xm

<?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="G://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里)-->

<!--我们在内存中缓存的element的最大数目满了时,把下面俩个改为true,允许保存在硬盘中,就会在本地文件夹保存-->
    <cache name="com/dhm/entity/User.java" eternal="false" maxElementsInMemory="1"
           overflowToDisk="true" diskPersistent="true" timeToIdleSeconds="0"
           timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
</ehcache>

测试:

package com.dhm.text;

import com.zking.util.EhcacheUtil;

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

演示结果:

 七、hibernate使用echcache作为二级缓存

1、一级缓存:

   又称为session级别的缓存

/**
	 * 同一个session,sql语句只生成一次,这里用到了一级缓存
	 */
	@Test
	public void test1() {
		Session session = SessionFactoryUtil.getSession();
		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();
	}

2、二级缓存

 sessionFactory级别的缓存

开启二级缓存:

①、在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>
        

  ②、在需要二级缓存的文件进行配置

例:User.hbm.xml:User.hbm.xml文件中name要与region内的路径要一样,并且和ehcache中的name的路径相同

三条SQL,三条数据,如果当我们的数据比较多时,这种查询方法还是比较浪费资源消耗性能的,我们可以利用hibernate的二级缓存来实现只出现一条执行语句

User.hbm.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-mapping>
<!-- 
    name:类的全限定名
    table:类的对应表
    id标签:
        name:类属性    type:类属性对应的java类型
        column:数据库列段
    priperty标签:
        name:类属性    type:类属性对应的java类型
        column:数据库列段  

 -->
     <class name="com.dhm.entity.User" table="t_hibernate_user">
             <cache usage="read-write" region="com.dhm.entity.User"/>
        

        <id name="id" type="java.lang.Integer" column="id">
            <generator class="assigned" />
        </id>
        <property name="userName" type="java.lang.String" column="user_name">
        </property>
        <property name="userPwd" type="java.lang.String" column="user_pwd">
        </property>
        <property name="realName" type="java.lang.String" column="real_name">
        </property>
        <property name="sex" type="java.lang.String" column="sex">
        </property>
        <property name="birthday" type="java.sql.Date" column="birthday">
        </property>
        <property insert="false" update="false" name="createDatetime"
            type="java.sql.Timestamp" column="create_datetime">
        </property>
        <property name="remark" type="java.lang.String" column="remark">
        </property>
    </class>        

</hibernate-mapping>

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="G://xxx"/>
    <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
                  timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>


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

/**
	 * 默认情况下,sql语句形成了三次,这里为了提高性能,必须使用二级缓存SessionFactory缓存
	 *  <!-- 开启二级缓存 -->
	 *  <property name="hibernate.cache.use_second_level_cache">true</property>
      <!-- 开启查询缓存 -->
      <property name="hibernate.cache.use_query_cache">true</property>
      <!-- EhCache驱动 -->
      	注意:此处必须用hibernate的5.2.12.Final 版本
      <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
      
      	映射文件中添加标签
      	<cache usage="read-write" region="com.zking.one.entity.User"/>
      	这里的region指的是Ehcache.xml中cacheName
	 * @param args
	 */
	@Test
	public void test2() {
		UserDao userDao  = new UserDao();
		User u = new User();
		u.setId(7);
		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);
		
	}

结果:

八、hibernate多条记录缓存

hibernate二级缓存不会同时缓存多条数据

我们可以设置Cacheable使用缓存

package com.dhm.text;

import java.util.List;

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

import com.zking.util.SessionFactoryUtil;


/**
 * hibernate二级缓存不会同时缓存多条数据
 * @author Administrator
 *
 */
public class EhcacheDemo4 {
	public static void main(String[] args) {
		Session session = SessionFactoryUtil.getSession();
		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();
	}
}

结果:

--------------------没有了---------------------- 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值