Mybatis集成ehcache

1.为什么需要缓存

拉高程序的性能

2. 什么样的数据需要缓存

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

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

3. ehcache是什么

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

ehcache的特点:

够快

Ehcache的发行有一段时长了,经过几年的努力和不计其数的性能测试,Ehcache终被设计于large, high concurrency systems.

够简单

开发者提供的接口非常简单明了,从Ehcache的搭建到运用运行仅仅需要的是你宝贵的几分钟。其实很多开发者都不知道自己用在用Ehcache,Ehcache被广泛的运用于其他的开源项目

够袖珍

关于这点的特性,官方给了一个很可爱的名字small foot print ,一般Ehcache的发布版本不会到2M,V 2.2.3 才 668KB。

够轻量

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

好扩展

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

监听器

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

分布式缓存

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

 ehcache的使用

导入相关依赖

 <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency> <!--mybatis与ehcache整合-->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency> <!--ehcache依赖-->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.0</version>
</dependency>

修改日志配置,因为ehcache使用了Slf4j作为日志输出

 <!-- log4j2日志配置相关依赖 -->
<log4j2.version>2.9.1</log4j2.version>
<log4j2.disruptor.version>3.2.0</log4j2.disruptor.version>
<slf4j.version>1.7.13</slf4j.version> <!-- log4j2日志相关依赖 -->
<!-- log配置:Log4j2 + Slf4j -->
<!-- slf4j核心包-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
<scope>runtime</scope>
</dependency> <!--核心log4j2jar包-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j2.version}</version>
</dependency>
<!--用于与slf4j保持桥接-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>${log4j2.version}</version>
</dependency>
<!--web工程需要包含log4j-web,非web工程不需要-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>${log4j2.version}</version>
<scope>runtime</scope>
</dependency> <!--需要使用log4j2的AsyncLogger需要包含disruptor-->
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>${log4j2.disruptor.version}</version>
</dependency>

在Resource中添加一个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>

mybaits的二级缓存是mapper范围级别,除了在SqlMapConfig.xml设置二级缓存的总开关,还要在具体的mapper.xml中开启二级缓存

开启mybatis的二级缓存

 <!--设置mybaits对缓存的支持-->
<property name="configurationProperties">
<props>
<!-- 全局映射器启用缓存 *主要将此属性设置完成即可-->
<prop key="cacheEnabled">true</prop>
<!-- 查询时,关闭关联对象即时加载以提高性能 -->
<prop key="lazyLoadingEnabled">false</prop>
<!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 -->
<prop key="aggressiveLazyLoading">true</prop>
</props>
</property>

在XxxMapper.xml中配置cache

 <cache type="org.mybatis.caches.ehcache.EhcacheCache">

可以通过select标签的useCache属性打开或关闭二级缓存

<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" useCache="false"></select>

mybatis集成redis

1. redis常用类

1.1 Jedis

jedis就是集成了redis的一些命令操作,封装了redis的java客户端

1.2 JedisPoolConfig

Redis连接池

1.3 ShardedJedis

基于一致性哈希算法实现的分布式Redis集群客户端

实现 mybatis 的二级缓存,一般来说有如下两种方式:

1) 采用 mybatis 内置的 cache 机制。

2) 采用三方 cache 框架, 比如ehcache, oscache 等等.

添加redis相关依赖

 <!-- redis与spring的整合依赖 -->
<redis.version>2.9.0</redis.version>
<redis.spring.version>1.7.1.RELEASE</redis.spring.version> <dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${redis.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>${redis.spring.version}</version>
</dependency>

log4j2配置

 <!-- jackson -->
<jackson.version>2.9.3</jackson.version> <!-- jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>

spring + redis 集成实现缓存功能(与mybatis无关)

添加两个redis的配置文件,并将redis.properties和applicationContext-redis.xml配置到applicationContext.xml文件中

redis.properties

applicationContext-redis.xml

注1:将redis.properties导入到applicationContext.xml文件中

spring中引入第二个属性文件会出现“找不到某个配置项”错误,这是因为spring只允许有一个<context:property-placeholder/>

<!--引入一个属性文件的写法-->

<context:property-placeholder ignore-unresolvable="true" location="classpath:jdbc.properties" />

<!--引入两个或多个属性文件的写法-->

<context:property-placeholder ignore-unresolvable="true" location="classpath:jdbc.properties,classpath:redis.properties" />

注2:通过import标签将applicationContext-redis.xml导入到applicationContext.xml文件中

<!--导入redis配置-->

<import resource="applicationContext-redis.xml"/>

redis.properties(连接redis数据库)

 redis.hostName=192.168.183.128
redis.port=6379
redis.password=****
redis.timeout=10000
redis.maxIdle=300
redis.maxTotal=1000
redis.maxWaitMillis=1000
redis.minEvictableIdleTimeMillis=300000
redis.numTestsPerEvictionRun=1024
redis.timeBetweenEvictionRunsMillis=30000
redis.testOnBorrow=true
redis.testWhileIdle=true

applicationContext-redis.xml

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 1. 引入properties配置文件 -->
<!--<context:property-placeholder location="classpath:redis.properties" />--> <!-- 2. redis连接池配置-->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!--最大空闲数-->
<property name="maxIdle" value="${redis.maxIdle}"/>
<!--连接池的最大数据库连接数 -->
<property name="maxTotal" value="${redis.maxTotal}"/>
<!--最大建立连接等待时间-->
<property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
<!--逐出连接的最小空闲时间 默认1800000毫秒(30分钟)-->
<property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/>
<!--每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3-->
<property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/>
<!--逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1-->
<property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/>
<!--是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个-->
<property name="testOnBorrow" value="${redis.testOnBorrow}"/>
<!--在空闲时检查有效性, 默认false -->
<property name="testWhileIdle" value="${redis.testWhileIdle}"/>
</bean> <!-- 3. redis连接工厂 -->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
destroy-method="destroy">
<property name="poolConfig" ref="poolConfig"/>
<!--IP地址 -->
<property name="hostName" value="${redis.hostName}"/>
<!--端口号 -->
<property name="port" value="${redis.port}"/>
<!--如果Redis设置有密码 -->
<property name="password" value="${redis.password}"/>
<!--客户端超时时间单位是毫秒 -->
<property name="timeout" value="${redis.timeout}"/>
</bean> <!-- 4. redis操作模板,使用该对象可以操作redis -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory"/>
<!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!! -->
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
</property>
<!--开启事务 -->
<property name="enableTransactionSupport" value="true"/>
</bean> <!-- 5.使用中间类解决RedisCache.RedisTemplate的静态注入,从而使MyBatis实现第三方缓存 -->
<bean id="redisCacheTransfer" class="com.Mybatis.util.RedisCacheTransfer">
<property name="redisTemplate" ref="redisTemplate"/>
</bean>
</beans>

applicationContext.xml配置

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--多数据源导入配置-->
<context:property-placeholder location="classpath:jdbc.properties,classpath:redis.properties" /> <!--整合mybatis框架-->
<import resource="applicationContext-mybatis.xml"></import>
<!--spring整合redis-->
<import resource="applicationContext-redis.xml"></import>
</beans>

创建mybatis的自定义缓存类“RedisCache”,必须实现org.apache.ibatis.cache.Cache接口

 package com.Mybatis.util;

 import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate; import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock; public class RedisCache implements Cache //实现类
{
private static final Logger logger = LoggerFactory.getLogger(RedisCache.class); private static RedisTemplate<String,Object> redisTemplate; private final String id; /**
* The {@code ReadWriteLock}.
*/
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); @Override
public ReadWriteLock getReadWriteLock()
{
return this.readWriteLock;
} public static void setRedisTemplate(RedisTemplate redisTemplate) {
RedisCache.redisTemplate = redisTemplate;
} public RedisCache(final String id) {
if (id == null) {
throw new IllegalArgumentException("Cache instances require an ID");
}
logger.debug("MybatisRedisCache:id=" + id);
this.id = id;
} @Override
public String getId() {
return this.id;
} @Override
public void putObject(Object key, Object value) {
try{
logger.info(">>>>>>>>>>>>>>>>>>>>>>>>putObject: key="+key+",value="+value);
if(null!=value)
redisTemplate.opsForValue().set(key.toString(),value,60, TimeUnit.SECONDS);
}catch (Exception e){
e.printStackTrace();
logger.error("redis保存数据异常!");
}
} @Override
public Object getObject(Object key) {
try{
logger.info(">>>>>>>>>>>>>>>>>>>>>>>>getObject: key="+key);
if(null!=key)
return redisTemplate.opsForValue().get(key.toString());
}catch (Exception e){
e.printStackTrace();
logger.error("redis获取数据异常!");
}
return null;
} @Override
public Object removeObject(Object key) {
try{
if(null!=key)
return redisTemplate.expire(key.toString(),1,TimeUnit.DAYS);
}catch (Exception e){
e.printStackTrace();
logger.error("redis获取数据异常!");
}
return null;
} @Override
public void clear() {
Long size=redisTemplate.execute(new RedisCallback<Long>() {
@Override
public Long doInRedis(RedisConnection redisConnection) throws DataAccessException {
Long size = redisConnection.dbSize();
//连接清除数据
redisConnection.flushDb();
redisConnection.flushAll();
return size;
}
});
logger.info(">>>>>>>>>>>>>>>>>>>>>>>>clear: 清除了" + size + "个对象");
} @Override
public int getSize() {
Long size = redisTemplate.execute(new RedisCallback<Long>() {
@Override
public Long doInRedis(RedisConnection connection)
throws DataAccessException {
return connection.dbSize();
}
});
return size.intValue();
}
}

静态注入中间类“RedisCacheTransfer”,解决RedisCache中RedisTemplate的静态注入,从而使MyBatis实现第三方缓存

 package com.Mybatis.util;

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate; public class RedisCacheTransfer {
@Autowired
public void setRedisTemplate(RedisTemplate redisTemplate) {
RedisCache.setRedisTemplate(redisTemplate);
}
}

测试

 /**
* 单个查询测试有无缓存
*/
@Test
public void testCacheOne() {
System.out.println(this.bookService.selectByPrimaryKey(22));
System.out.println(this.bookService.selectByPrimaryKey(22));
} /**
* 多个查询测试有无缓存
*/
@Test
public void testCacheMany() {
Book book = new Book();
//带条件分页查询
book.setBname(StringUtil.toLikeStr("圣墟"));
PageBean pageBean = new PageBean();
//不分页
// pageBean.setPagination(false);
//根据页码分页查询
pageBean.setPage(2);
List<Book> books = bookService.listPager(book, pageBean);
for (Book b : books) {
System.out.println(b);
} List<Book> books2 = bookService.listPager(book, pageBean);
for (Book b : books2) {
System.out.println(b);
} }

Thanks for watching!!!

Mybatis集成ehcache的更多相关文章

  1. SpringMVC4集成ehcache

    前言 使用SpringMVC4集成ehcache来缓存服务器数据. 开发环境 SpringMVC4.ehcache2.6. 项目结构 SpringMVC 集成ehcache 1.pom.xml //除 ...

  2. (37)Spring Boot集成EHCache实现缓存机制【从零开始学Spring Boot】

    [本文章是否对你有用以及是否有好的建议,请留言] 写后感:博主写这么一系列文章也不容易啊,请评论支持下. 如果看过我之前(35)的文章这一篇的文章就会很简单,没有什么挑战性了. 那么我们先说说这一篇文 ...

  3. MyBatis6:MyBatis集成Spring事物管理(下篇)

    前言 前一篇文章<MyBatis5:MyBatis集成Spring事物管理(上篇)>复习了MyBatis的基本使用以及使用Spring管理MyBatis的事物的做法,本文的目的是在这个的基 ...

  4. mybatis0210 mybatis和ehcache缓存框架整合

    .1mybatis和ehcache缓存框架整合 一般不用mybatis来管理缓存而是用其他缓存框架在管理缓存,因为其他缓存框架管理缓存会更加高效,因为别人专业做缓存的而mybatis专业做sql语句的 ...

  5. MyBatis6:MyBatis集成Spring事务管理(下篇)

    前言 前一篇文章<MyBatis5:MyBatis集成Spring事务管理(上篇)>复习了MyBatis的基本使用以及使用Spring管理MyBatis的事务的做法,本文的目的是在这个的基 ...

  6. maven,spring,mybatis集成错误

    maven,spring,mybatis集成的时候单元测试junit测试没问题,但mvn jetty:run 就报错误 错误: org.apache.ibatis.binding.BindingExc ...

  7. mybatis 与 ehcache 整合[转]

    1.简介 MyBatis 是支持普通SQL 查询,存储过程和高级映射的优秀持久层框架.MyBatis 消除了几乎所有的JDBC 代码和参数的手工设置以及结果集的检索. Ehcache 是现在最流行的纯 ...

  8. spring springMVC mybatis 集成

    最近闲来无事,整理了一下spring springMVC mybatis 集成,关于这个话题在园子里已经有很多人写过了,我主要是想提供一个完整的demo,涵盖crud,事物控制等. 整个demo分三个 ...

  9. 使用MyBatis集成阿里巴巴druid连接池(不使用spring)

    在工作中发现mybatis默认的连接池POOLED,运行时间长了会报莫名其妙的连接失败错误.因此采用阿里巴巴的Druid数据源(码云链接 ,中文文档链接). mybatis更多数据源参考博客链接 . ...

随机推荐

  1. SpringBoot 系列教程自动配置选择生效

    191214-SpringBoot 系列教程自动配置选择生效 写了这么久的 Spring 系列博文,发现了一个问题,之前所有的文章都是围绕的让一个东西生效:那么有没有反其道而行之的呢? 我们知道可以通 ...

  2. ext.net 这两个id不是同一个对象,小心!

    今天遇到了一个很奇怪的问题,查到最后发现是下面代码原因 代码中使用store存储js对象 mcp_liststore.data.items[3].id mcp_liststore.data.get(3 ...

  3. C# Thread was being aborted

    先重现问题 1.新建一个aspx页面项目,插入两个页面WebForm1.aspx,WebForm2.aspx, WebForm1代码修改如下 protected void Page_Load(obje ...

  4. 关于优秀的视频播放器 - PotPlayer

    播放器设置 直接截图: 其他重要功能 1. 切换语音:Alt + A 谢谢浏览!

  5. 用pyenv管理Python多版本及下载加速方法--Mac上

    原文:https://www.jianshu.com/p/91fc7ecc5e46 先大致介绍下pyenv的安装及配置流程.随后介绍加速下载方法 安装: brew install pyenv 配置 在 ...

  6. CSS加载会阻塞页面显示?

    可能大家都知道,js执行会阻塞DOM树的解析和渲染,那么css加载会阻塞DOM树的解析和渲染吗?接下来,我们就一起来分析一下. 原理解析 那么为什么会出现上面的现象呢?我们从浏览器的渲染过程来解析下. ...

  7. SQL Server 2014查看服务器数据库字段报错 (Microsoft.SqlServer.Management.Sdk.Sfc)

    报错信息 无法为该请求检索数据. (Microsoft.SqlServer.Management.Sdk.Sfc) 未知属性 IsMemoryOptimized (Microsoft.SqlServe ...

  8. Sqlserver表值函数来获取逗号分隔的ID

    其功能为: 将字符串如'1,2,3,4,5,6' 拼接成SQL里面的id 1:使用: select * from Student where id IN( SELECT * FROM dbo.F_SP ...

  9. python 数据结构之图的储存方式

    参考链接:https://blog.csdn.net/u014281392/article/details/79120406 所描述的图的结构为: 下面介绍不同的储存方式,我想不必详细分别是每个名称都 ...

  10. 来看一下Java中“-”与equeals的区别

    简介: == ==是比较两个变量的值,如果是基本数据类型,那么就是比较的基本数据的大小值 情况一 int a=1; int b=1; System.out.println(a==b); 以上图中:== ...