Mybatis整合ehcache,Redis实现二级缓存

2024-04-21 14:38

本文主要是介绍Mybatis整合ehcache,Redis实现二级缓存,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录:
mybatis整合ehcache
1.pom依赖
2.ehcache.xml
3.applicationContext-mybatis.xml(mybatis.cfg.xml)中去开启二级缓存
4.需要在xxxMapper.xml中配置
5.对比缓存单个与缓存多个的区别
mybatis整合redis
1.pom依赖 redis
2.redis.properties
3.applicationContext-redis将spring与redis整合
注册redis.properties
配置redispool
配置connectFactory
配置数据序列化方式
借助spring完成mybatis与redis的衔接的工具

mybatis整合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的使用
    3.1 导入相关依赖

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

1.pom依赖

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

日志我们使用slf4j,并用log4j来实现。SLF4J不同于其他日志类库,与其它有很大的不同。
SLF4J(Simple logging Facade for Java)不是一个真正的日志实现,而是一个抽象层( abstraction layer),
它允许你在后台使用任意一个日志类库。

2.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>

3.applicationContext-mybatis.xml(mybatis.cfg.xml)中去开启二级缓存

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

4.需要在xxxMapper.xml中配置

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

在这里插入图片描述
5.对比缓存单个与缓存多个的区别
测试代码:

 @Testpublic void cacheMany() {Map map = new HashMap();map.put("bname", StringUtils.toLikeStr("不死不灭"));List<Map> aaaa = this.bookService.listPager(map,pageBean);for (Map m : aaaa) {System.out.println(m);}List<Map> aaaa2 = this.bookService.listPager(map,pageBean);for (Map m : aaaa2) {System.out.println(m);}}@Testpublic void cacheSimgle() {Book b1 = this.bookService.selectByPrimaryKey(29);System.out.println(b1);Book b2 = this.bookService.selectByPrimaryKey(29);System.out.println(b2);}

多个:
在这里插入图片描述
单个:
在这里插入图片描述
我们可以发现,单个 多个 二次加载都有缓存。
如果想不使用缓存,在sqly语句后加上useCache=“false”
在这里插入图片描述

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 等等.

1.pom依赖 redis

<properties><!-- redis与spring的整合依赖 --><redis.version>2.9.0</redis.version><redis.spring.version>1.7.1.RELEASE</redis.spring.version><!-- jackson --><jackson.version>2.9.3</jackson.version></properties><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><!-- 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>

2.redis.properties

redis.hostName=192.168.176.128
redis.port=6379
redis.password=123456
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

3.applicationContext-redis将spring与redis整合
applicationContext-mybatis.xml中:
我们需要注释这行代码:
在这里插入图片描述
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" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop"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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"><context:property-placeholder location="classpath:jdbc.properties,classpath:redis.properties"/><!--整合mybatids--><import resource="applicationContext-mybatis.xml"></import><!--整合redis--><import resource="applicationContext-redis.xml"></import>
</beans>

applicationContext-redis.xml

注册redis.properties 配置redispool 配置connectFactory

<?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.ly.util.RedisCacheTransfer"><property name="redisTemplate" ref="redisTemplate"/></bean>
</beans>

配置数据序列化方式:
在实体类实现接口:
在这里插入图片描述
工具类
有两个:
RedisCache:

package com.ly.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();@Overridepublic 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;}@Overridepublic String getId() {return this.id;}@Overridepublic void putObject(Object key, Object value) {try{logger.info(">>>>>>>>>>>>>>>>>>>>>>>>putObject: key="+key+",value="+value);if(null!=value)redisTemplate.opsForValue().set(key.toString(),value,2, TimeUnit.DAYS);}catch (Exception e){e.printStackTrace();logger.error("redis保存数据异常!");}}@Overridepublic 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;}@Overridepublic 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;}@Overridepublic void clear() {Long size=redisTemplate.execute(new RedisCallback<Long>() {@Overridepublic Long doInRedis(RedisConnection redisConnection) throws DataAccessException {Long size = redisConnection.dbSize();//连接清除数据redisConnection.flushDb();redisConnection.flushAll();return size;}});logger.info(">>>>>>>>>>>>>>>>>>>>>>>>clear: 清除了" + size + "个对象");}@Overridepublic int getSize() {Long size = redisTemplate.execute(new RedisCallback<Long>() {@Overridepublic Long doInRedis(RedisConnection connection)throws DataAccessException {return connection.dbSize();}});return size.intValue();}
}

RedisCacheTransfer

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

测试:

 @Testpublic void cacheSimgle() {Book b1 = this.bookService.selectByPrimaryKey(29);System.out.println(b1);Book b2 = this.bookService.selectByPrimaryKey(29);System.out.println(b2);}

可以看到redis中有了缓存数据,并且有时间限制失效
在这里插入图片描述

这篇关于Mybatis整合ehcache,Redis实现二级缓存的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/923315

相关文章

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

PyCharm中配置PyQt的实现步骤

《PyCharm中配置PyQt的实现步骤》PyCharm是JetBrains推出的一款强大的PythonIDE,结合PyQt可以进行pythion高效开发桌面GUI应用程序,本文就来介绍一下PyCha... 目录1. 安装China编程PyQt1.PyQt 核心组件2. 基础 PyQt 应用程序结构3. 使用 Q

Redis MCP 安装与配置指南

《RedisMCP安装与配置指南》本文将详细介绍如何安装和配置RedisMCP,包括快速启动、源码安装、Docker安装、以及相关的配置参数和环境变量设置,感兴趣的朋友一起看看吧... 目录一、Redis MCP 简介二、安www.chinasem.cn装 Redis MCP 服务2.1 快速启动(推荐)2.

Python实现批量提取BLF文件时间戳

《Python实现批量提取BLF文件时间戳》BLF(BinaryLoggingFormat)作为Vector公司推出的CAN总线数据记录格式,被广泛用于存储车辆通信数据,本文将使用Python轻松提取... 目录一、为什么需要批量处理 BLF 文件二、核心代码解析:从文件遍历到数据导出1. 环境准备与依赖库