二级缓存
1. 为什么需要缓存
拉高程序的性能
2、数据库类型:
关系型数据库:数据与数据之间存在关系(联系)的数据库 mysql/Oracle、sqlserver
非关系型数据库:数据与数据之间是不存在关系的,key-value
1、基于文件存储的数据库:ehcache
2、基于内存存储的数据库:redis、memcache
3、基于文档存储的数据库:mongodb
3、 什么样的数据需要缓存
很少被修改或根本不改的数据 数据字典
业务场景比如:耗时较高的统计分析sql、电话账单查询sql等
4、 ehcache是什么
Ehcache 是现在最流行的纯Java开源缓存框架,配置简单、结构清晰、功能强大
注1:本章介绍的是2.X版本,3.x的版本和2.x的版本API差异比较大
5、 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开始,支持高性能的分布式缓存,兼具灵活性和扩展性
6、 ehcache的使用
3.1 导入相关依赖
net.sf.ehcache
ehcache
2.10.0
3.2 核心接口
CacheManager:缓存管理器
Cache:缓存对象,缓存管理器内可以放置若干cache,存放数据的实质,所有cache都实现了Ehcache接口
Element:单条缓存数据的组成单位
3.3 src:ehcache.xml
5.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>
5.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);//手动开启二级缓存
7、log4j2
异步
/8、slf4j 抽象的日志系统
slf4j
log4j2/common logging
案例:
缓存原理
package com.zking.nine.test;
import java.util.HashMap;
import java.util.Map;
/**
* 缓存的原理
* @author Administrator
*
*/
public class EhcacheTest1 {
static Map<String, Object> map=new HashMap<String, Object>();
public static Object getValue(String key) {
Object value = map.get(key);
if(value==null) {
System.out.println("查数据库!!!");
map.put(key, "权限相关的数据");
value=map.get(key);
}
return value;
}
/**
* 以权限为例
* 张三、李四都属于学生角色
* 注意:张三李四看到的菜单都是一样的
*
* 希望:
* 1、张三进来查数据库,拿到对应的菜单信息 从数据拿
* 2、李四进来,既然看到的东西是一样的,查数据库耗性能,能拿到跟张三一样的信息
* 并且不访问数据库
* 办法:张三访问的时间把信息放到缓存中
* @param args
*/
public static void main(String[] args) {
System.out.println(getValue("menus"));
System.out.println(getValue("menus"));
//结果:查数据库!!! 权限相关的数据 权限相关的数据
}
}
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="E:\temp"/>
<!--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.zking.one.entity.User" eternal="false" maxElementsInMemory="1"
overflowToDisk="true" diskPersistent="false" timeToIdleSeconds="0"
timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
</ehcache>
utildemo
package com.zking.nine.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.zking.nine.test;
import java.util.HashMap;
import java.util.Map;
import com.zking.nine.util.EhcacheUtil;
public class EhcacheTest2 {
public static void main(String[] args) {
/**
* 新增一个槽,如果没有给他设置特定的规则,那么他就会使用默认的
*/
System.out.println(System.getProperty("java.io.tmpdir"));
EhcacheUtil.put("stuCache2", 1, "aaa");
EhcacheUtil.put("stuCache2", 2, "bbb");
System.out.println(EhcacheUtil.get("stuCache2", 2));
}
}
//在ehcache.xml里
<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="1"
overflowToDisk="true" diskPersistent="false" timeToIdleSeconds="0"
timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/><!--自己设定的-->
slf4j介绍
<!-- log配置:Log4j2 + Slf4j -->
<!-- slf4j核心包 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<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>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.9.1</version>
</dependency>
hibernate整合ehcache查单个
(注:hibernate-core的版本要与hibernate-ehcache的版本相对应)
1、导jar包
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.2.12.Final</version>
</dependency>
package com.zking.nine.test;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.zking.nine.util.EhcacheUtil;
import com.zking.one.entity.User;
import com.zking.two.util.SessionFactoryUtils;
/**
* hibernate整合ehcache完成查询单个用户
* @author Administrator
*
*/
public class EhcacheTest3 {
public static void main(String[] args) {
Session session = SessionFactoryUtils.getSession();
Transaction transaction = session.beginTransaction();
User user = session.get(User.class, 2);
System.out.println(user);
User user2 = session.get(User.class, 2);
System.out.println(user2);
User user3 = session.get(User.class, 2);
System.out.println(user3);
transaction.commit();
session.close();
}
}
查所有(二级缓存)
1、在实体类里设置userCache
private boolean userCache=false;//是否缓存
//实现set/get方法
2、在xxx.hbm.xml里配置
<cache usage="read-write" region="com.zking.one.entity.User"></cache>
3、在hibernate.cfg.xml里配置二级缓存
<!-- 配置本地事务(No CurrentSessionContext configured!) -->
<property name="hibernate.current_session_context_class">thread</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>
<!-- 2. 调试相关 -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
4、在ehcache.xml里设置规定
<cache name="com.zking.one.entity.User" eternal="false" maxElementsInMemory="1"
overflowToDisk="true" diskPersistent="false" timeToIdleSeconds="0"
timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
5、测试
package com.zking.nine.test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import com.zking.nine.util.EhcacheUtil;
import com.zking.one.entity.User;
import com.zking.two.util.SessionFactoryUtils;
/**
* hibernate整合ehcache完成查询多个用户
* @author Administrator
*
*/
public class EhcacheTest4 {
public static void main(String[] args) {
Session session = SessionFactoryUtils.getSession();
Transaction transaction = session.beginTransaction();
Query query = session.createQuery("from User");
User user=new User();
user.setUserCache(true);
/**
* 使用dao方法的时候,使用ehcache缓存,默认查多条记录是不是使用缓存
*/
if(user.isUserCache()) {
query.setCacheable(true);
}
List list =query.list();
System.out.println(list.size());
List list2=query.list();
query.setCacheable(false);
System.out.println(list2.size());
List list3 =query.list();
query.setCacheable(true);
System.out.println(list3.size());
transaction.commit();
session.close();
}
}