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开始,支持高性能的分布式缓存,兼具灵活性和扩展性
3. ehcache的使用
3.1 导入相关依赖
3.2 核心接口
CacheManager:缓存管理器
Cache:缓存对象,缓存管理器内可以放置若干cache,存放数据的实质,所有cache都实现了Ehcache接口
Element:单条缓存数据的组成单位
4. ssm中整合ehcache
4.1 导入相关依赖
修改日志配置,因为ehcache使用了Slf4j作为日志输出
日志我们使用slf4j,并用log4j来实现。SLF4J不同于其他日志类库,与其它有很大的不同。
1<!--spring对ehcache的相关支持--> 2 <dependency> 3 <groupId>org.springframework</groupId> 4 <artifactId>spring-context-support</artifactId> 5 <version>${spring.version}</version> 6 </dependency> 7 8 <!--mybatis与ehcache整合--> 9 <dependency> 10 <groupId>org.mybatis.caches</groupId> 11 <artifactId>mybatis-ehcache</artifactId> 12 <version>1.1.0</version> 13 </dependency> 14 15 <!--ehcache依赖--> 16 <dependency> 17 <groupId>net.sf.ehcache</groupId> 18 <artifactId>ehcache</artifactId> 19 <version>2.10.0</version> 20 </dependency> 21 22<!--lofj2--> 23 <!-- log配置:Log4j2 + Slf4j --> 24 <!-- slf4j核心包 --> 25 <dependency> 26 <groupId>org.slf4j</groupId> 27 <artifactId>slf4j-api</artifactId> 28 <version>1.7.7</version> 29 </dependency> 30 <dependency> 31 <groupId>org.slf4j</groupId> 32 <artifactId>jcl-over-slf4j</artifactId> 33 <version>1.7.7</version> 34 <scope>runtime</scope> 35 </dependency>
添加一个ehcache.xml的配置文件
1<?xml version="1.0" encoding="UTF-8"?> 2<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" 4 updateCheck="false"> 5 <!--磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存--> 6 <!--path:指定在硬盘上存储对象的路径--> 7 <!--java.io.tmpdir 是默认的临时文件路径。 可以通过如下方式打印出具体的文件路径 System.out.println(System.getProperty("java.io.tmpdir"));--> 8 <diskStore path="java.io.tmpdir"/> 9 10 11 <!--defaultCache:默认的管理策略--> 12 <!--eternal:设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断--> 13 <!--maxElementsInMemory:在内存中缓存的element的最大数目--> 14 <!--overflowToDisk:如果内存中数据超过内存限制,是否要缓存到磁盘上--> 15 <!--diskPersistent:是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false--> 16 <!--timeToIdleSeconds:对象空闲时间(单位:秒),指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问--> 17 <!--timeToLiveSeconds:对象存活时间(单位:秒),指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问--> 18 <!--memoryStoreEvictionPolicy:缓存的3 种清空策略--> 19 <!--FIFO:first in first out (先进先出)--> 20 <!--LFU:Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存--> 21 <!--LRU:Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存--> 22 <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false" 23 timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/> 24 25 26 <!--name: Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)--> 27 <!--<cache name="stuCache" eternal="false" maxElementsInMemory="100" 28 overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" 29 timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>--> 30</ehcache>
在applicationContext.xml中加入chache配置
1<!-- 使用ehcache缓存 --> 2 <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> 3 <property name="configLocation" value="classpath:ehcache.xml"/> 4 <property name="shared" value="true"></property> 5 </bean> 6 <!-- 默认是cacheManager --> 7 <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> 8 <property name="cacheManager" ref="cacheManagerFactory"/> 9 </bean>
开启mybatis的二级缓存
applicationContext-mybatis.xml中添加
1!--设置mybaits对缓存的支持--> 2 <property name="configurationProperties"> 3 <props> 4 <!-- 全局映射器启用缓存 *主要将此属性设置完成即可--> 5 <prop key="cacheEnabled">true</prop> 6 <!-- 查询时,关闭关联对象即时加载以提高性能 --> 7 <prop key="lazyLoadingEnabled">false</prop> 8 <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 --> 9 <prop key="aggressiveLazyLoading">true</prop> 10 </props> 11 </property>
BookMapper.xml里面添加
1<cache type="org.mybatis.caches.ehcache.EhcacheCache"> 2 <property name="timeToIdleSeconds" value="3600"/> 3 <property name="timeToLiveSeconds" value="3600"/> 4 <property name="maxEntriesLocalHeap" value="1000"/> 5 <property name="maxEntriesLocalDisk" value="10000000"/> 6 <property name="memoryStoreEvictionPolicy" value="LRU"/> 7 </cache>

Mybatis集成redis
1.添加pom依赖
1<!--redis--> 2 <dependency> 3 <groupId>redis.clients</groupId> 4 <artifactId>jedis</artifactId> 5 <version>${redis.version}</version> 6 </dependency> 7 <dependency> 8 <groupId>org.springframework.data</groupId> 9 <artifactId>spring-data-redis</artifactId> 10 <version>${redis.spring.version}</version> 11 </dependency> 12 13 14 15 <!-- jackson --> 16 <dependency> 17 <groupId>com.fasterxml.jackson.core</groupId> 18 <artifactId>jackson-databind</artifactId> 19 <version>${jackson.version}</version> 20 </dependency> 21 <dependency> 22 <groupId>com.fasterxml.jackson.core</groupId> 23 <artifactId>jackson-core</artifactId> 24 <version>${jackson.version}</version> 25 </dependency> 26 <dependency> 27 <groupId>com.fasterxml.jackson.core</groupId> 28 <artifactId>jackson-annotations</artifactId> 29 <version>${jackson.version}</version> 30 </dependency>
注:
版本冲突问题:
1. ClassNotFoundException : redis/client/util/geoUtils 说这个类找不到。
2. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisTemplate' defined in class path resource [applicationContext.xml]
说创建 redisTemplate bean 对象时失败了。
redis.client 2.9.0 ---- spring-data-redis 1.7.1.RELEASE
redis.client 2.9.0 ---- spring-data-redis 1.7.2.RELEASE 这两个是可以使用的
log4j2配置
spring + redis 集成实现缓存功能(与mybatis无关)
添加两个redis的配置文件,并将redis.properties和applicationContext-redis.xml配置到applicationContext.xml文件中
注:
spring中引入第二个属性文件会出现“找不到某个配置项”错误,这是因为spring只允许有一个
redis.properties
1redis.hostName=192.168.197.128 2redis.port=6379 3redis.password=123456 4redis.timeout=10000 5redis.maxIdle=300 6redis.maxTotal=1000 7redis.maxWaitMillis=1000 8redis.minEvictableIdleTimeMillis=300000 9redis.numTestsPerEvictionRun=1024 10redis.timeBetweenEvictionRunsMillis=30000 11redis.testOnBorrow=true 12redis.testWhileIdle=true
applicationContext-redis.xml
1<?xml version="1.0" encoding="UTF-8"?> 2<beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 5 6 <!-- 1. 引入properties配置文件 --> 7 <!--<context:property-placeholder location="classpath:redis.properties" />--> 8 9 <!-- 2. redis连接池配置--> 10 <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> 11 <!--最大空闲数--> 12 <property name="maxIdle" value="${redis.maxIdle}"/> 13 <!--连接池的最大数据库连接数 --> 14 <property name="maxTotal" value="${redis.maxTotal}"/> 15 <!--最大建立连接等待时间--> 16 <property name="maxWaitMillis" value="${redis.maxWaitMillis}"/> 17 <!--逐出连接的最小空闲时间 默认1800000毫秒(30分钟)--> 18 <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/> 19 <!--每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3--> 20 <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/> 21 <!--逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1--> 22 <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/> 23 <!--是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个--> 24 <property name="testOnBorrow" value="${redis.testOnBorrow}"/> 25 <!--在空闲时检查有效性, 默认false --> 26 <property name="testWhileIdle" value="${redis.testWhileIdle}"/> 27 </bean> 28 29 <!-- 3. redis连接工厂 --> 30 <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" 31 destroy-method="destroy"> 32 <property name="poolConfig" ref="poolConfig"/> 33 <!--IP地址 --> 34 <property name="hostName" value="${redis.hostName}"/> 35 <!--端口号 --> 36 <property name="port" value="${redis.port}"/> 37 <!--如果Redis设置有密码 --> 38 <property name="password" value="${redis.password}"/> 39 <!--客户端超时时间单位是毫秒 --> 40 <property name="timeout" value="${redis.timeout}"/> 41 </bean> 42 43 <!-- 4. redis操作模板,使用该对象可以操作redis --> 44 <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> 45 <property name="connectionFactory" ref="connectionFactory"/> 46 <!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!! --> 47 <property name="keySerializer"> 48 <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> 49 </property> 50 <property name="valueSerializer"> 51 <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/> 52 </property> 53 <property name="hashKeySerializer"> 54 <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> 55 </property> 56 <property name="hashValueSerializer"> 57 <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/> 58 </property> 59 <!--开启事务 --> 60 <property name="enableTransactionSupport" value="true"/> 61 </bean> 62 63 <!-- 5.使用中间类解决RedisCache.RedisTemplate的静态注入,从而使MyBatis实现第三方缓存 --> 64 <bean id="redisCacheTransfer" class="com.hmc.ssm.redis.RedisCacheTransfer"> 65 <property name="redisTemplate" ref="redisTemplate"/> 66 </bean> 67</beans>
applicationContext.xml
1<!--1. 引入外部多文件方式 --> 2 <bean id="propertyConfigurer" 3 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 4 <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /> 5 <property name="ignoreResourceNotFound" value="true" /> 6 <property name="locations"> 7 <list> 8 <value>classpath:jdbc.properties</value> 9 <value>classpath:redis.properties</value> 10 </list> 11 </property> 12 </bean> 13 <import resource="spring-mybatis.xml"/> 14 <import resource="mybatis-ehcache.xml"/> 15 <import resource="spring-redis.xml"/>
将redis缓存引入到mybatis中
创建mybatis的自定义缓存类“RedisCache”,必须实现org.apache.ibatis.cache.Cache接口
RedisCache.java
1package com.hmc.ssm.redis; 2 3 4import org.apache.ibatis.cache.Cache; 5import org.slf4j.Logger; 6import org.slf4j.LoggerFactory; 7import org.springframework.dao.DataAccessException; 8import org.springframework.data.redis.connection.RedisConnection; 9import org.springframework.data.redis.core.RedisCallback; 10import org.springframework.data.redis.core.RedisTemplate; 11 12import java.util.concurrent.TimeUnit; 13import java.util.concurrent.locks.ReadWriteLock; 14import java.util.concurrent.locks.ReentrantReadWriteLock; 15 16 17public class RedisCache implements Cache //实现类 18{ 19 private static final Logger logger = LoggerFactory.getLogger(RedisCache.class); 20 21 private static RedisTemplate<String,Object> redisTemplate; 22 23 private final String id; 24 25 /** 26 * The {@code ReadWriteLock}. 27 */ 28 private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); 29 30 @Override 31 public ReadWriteLock getReadWriteLock() 32 { 33 return this.readWriteLock; 34 } 35 36 public static void setRedisTemplate(RedisTemplate redisTemplate) { 37 RedisCache.redisTemplate = redisTemplate; 38 } 39 40 public RedisCache(final String id) { 41 if (id == null) { 42 throw new IllegalArgumentException("Cache instances require an ID"); 43 } 44 logger.debug("MybatisRedisCache:id=" + id); 45 this.id = id; 46 } 47 48 @Override 49 public String getId() { 50 return this.id; 51 } 52 53 @Override 54 public void putObject(Object key, Object value) { 55 try{ 56 logger.info(">>>>>>>>>>>>>>>>>>>>>>>>putObject:value="+value); 57 logger.info(">>>>>>>>>>>>>>>>>>>>>>>>putObject: key="+key+",value="+value); 58 if(null!=value) 59 redisTemplate.opsForValue().set(key.toString(),value,2, TimeUnit.DAYS); 60 }catch (Exception e){ 61 e.printStackTrace(); 62 logger.error("redis保存数据异常!"); 63 } 64 } 65 66 @Override 67 public Object getObject(Object key) { 68 try{ 69 logger.info(">>>>>>>>>>>>>>>>>>>>>>>>getObject: key="+key); 70 if(null!=key) 71 return redisTemplate.opsForValue().get(key.toString()); 72 }catch (Exception e){ 73 e.printStackTrace(); 74 logger.error("redis获取数据异常!"); 75 } 76 return null; 77 } 78 79 @Override 80 public Object removeObject(Object key) { 81 try{ 82 if(null!=key) 83 return redisTemplate.expire(key.toString(),1,TimeUnit.DAYS); 84 }catch (Exception e){ 85 e.printStackTrace(); 86 logger.error("redis获取数据异常!"); 87 } 88 return null; 89 } 90 91 @Override 92 public void clear() { 93 Long size=redisTemplate.execute(new RedisCallback<Long>() { 94 @Override 95 public Long doInRedis(RedisConnection redisConnection) throws DataAccessException { 96 Long size = redisConnection.dbSize(); 97 //连接清除数据 98 redisConnection.flushDb(); 99 redisConnection.flushAll(); 100 return size; 101 } 102 }); 103 logger.info(">>>>>>>>>>>>>>>>>>>>>>>>clear: 清除了" + size + "个对象"); 104 } 105 106 @Override 107 public int getSize() { 108 Long size = redisTemplate.execute(new RedisCallback<Long>() { 109 @Override 110 public Long doInRedis(RedisConnection connection) 111 throws DataAccessException { 112 return connection.dbSize(); 113 } 114 }); 115 return size.intValue(); 116 } 117}
RedisCacheTransfer.java
静态注入中间类“RedisCacheTransfer”,解决RedisCache中RedisTemplate的静态注入,从而使MyBatis实现第三方缓存
1package com.hmc.ssm.redis; 2 3import org.springframework.beans.factory.annotation.Autowired; 4import org.springframework.data.redis.core.RedisTemplate; 5 6public class RedisCacheTransfer { 7 @Autowired 8 public void setRedisTemplate(RedisTemplate redisTemplate) { 9 RedisCache.setRedisTemplate(redisTemplate); 10 } 11} 12 13在BookMapper.xml添加 14 15<cache type="com.zking.ssm.redis.RedisCache"/>



