核心关键在于定义一个RedisCache实现mytis实现的Cache接口

 **
* @author tele
* @Description RedisCache由于需要传入id, 由mybatis进行创建,所以如果需要为RedisCache注入RedisTemplateUtil,直接使用@Autowired无效
* @create 2019-09-07
*/
public class RedisCache implements Cache { private static RedisTemplateUtil templateUtil; public static void setTemplateUtil(RedisTemplateUtil templateUtil) {
RedisCache.templateUtil = templateUtil;
} //这个id实际是传入的mapper全限定名
private final String id; public RedisCache(final String id) {
if (id == null) {
throw new IllegalArgumentException("Cache instances require an ID");
}
this.id = id;
} public String getId() {
return id;
} public void putObject(Object key, Object value) {
templateUtil.set(key, value);
} public Object getObject(Object key) {
return templateUtil.get(key);
} public Object removeObject(Object key) {
return null;
} public void clear() {
templateUtil.clear();
} public int getSize() {
return templateUtil.getSize();
} public ReadWriteLock getReadWriteLock() {
return null;
}
}

定义中间类,注入工具类

 @Component
public class RedisCacheTransfer {
@Autowired
private RedisTemplateUtil redisTemplateUtil; @Autowired
public void setRedisTemplateUtil(){
RedisCache.setTemplateUtil(redisTemplateUtil);
}
}

工具类

 /**
* @author tele
* @Description
* @create 2019-09-09
*/
@Component
public class RedisTemplateUtil {
@Autowired
private RedisTemplate template; public Object get(Object key) {
return template.opsForValue().get(key);
} public void set(Object key,Object value){
template.opsForValue().set(key, value);
} public int getSize() {
int size = (int) template.execute((RedisCallback<Integer>) connection -> {
return connection.dbSize().intValue();
});
return size;
} public void clear() {
template.execute((RedisCallback) connection -> {
connection.flushDb();
return null;
});
}
}

在对应的mapper.xml中添加cache标签

测试的时候还是先加载ClassPathXmlContext,然后获得sqlSession,注意mybatis的增删改,flushCache=true,可如果你没有调用commit并不会清空缓存

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:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
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/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <context:component-scan base-package="cn.tele"/> <context:property-placeholder location="classpath:redis.properties,db.properties"/> <!--数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${db.url}"/>
<property name="driverClass" value="${db.driver}"/>
<property name="user" value="${db.username}"/>
<property name="password" value="${db.password}"/>
<property name="initialPoolSize" value="${db.initialPoolSize}"/>
<property name="maxPoolSize" value="${db.maxPoolSize}"/>
<property name="maxIdleTime" value="${db.maxIdleTime}"/>
<property name="idleConnectionTestPeriod" value="${db.idleConnectionTestPeriod}"/>
<property name="testConnectionOnCheckout" value="true"/>
</bean> <!--mybatis-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="mapperLocations" value="classpath*:cn/tele/bean/**/*.xml"/>
<property name="dataSource" ref="dataSource"/>
<property name="configurationProperties">
<props>
<prop key="cacheEnabled">true</prop>
<prop key="jdbcTypeForNull">NULL</prop>
<prop key="lazyLoadingEnabled">true</prop>
<prop key="aggressiveLazyLoading">false</prop>
</props>
</property>
</bean> <!--扫描mapper-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="cn.tele"/>
</bean> <!--redis连接池属性设置-->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}"/>
<property name="maxTotal" value="${redis.maxTotal}"/>
</bean> <bean id="jedisConnFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:poolConfig-ref="poolConfig" p:port="${redis.port}" p:hostName="${redis.host}"/> <bean id="redisTemplate"
class="org.springframework.data.redis.core.StringRedisTemplate"
p:connection-factory-ref="jedisConnFactory">
<!--序列化策略-->
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer">
<constructor-arg type="java.lang.Class" value="java.lang.String"/>
</bean>
</property> <property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"> </bean>
</property> <property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property> <property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>
</property>
</bean>
</beans>

mybatis 整合redis作为二级缓存的更多相关文章

  1. Mybatis整合Redis实现二级缓存

    Mybatis集成ehcache . 为什么需要缓存 拉高程序的性能 . 什么样的数据需要缓存 很少被修改或根本不改的数据 业务场景比如:耗时较高的统计分析sql.电话账单查询sql等 . ehcac ...

  2. SSM+redis整合(mybatis整合redis做二级缓存)

    SSM:是Spring+Struts+Mybatis ,另外还使用了PageHelper 前言: 这里主要是利用redis去做mybatis的二级缓存,mybaits映射文件中所有的select都会刷 ...

  3. mybatis 使用redis实现二级缓存(spring boot)

    mybatis 自定义redis做二级缓存 前言 如果关注功能实现,可以直接看功能实现部分 何时使用二级缓存 一个宗旨---不常变的稳定而常用的 一级是默认开启的sqlsession级别的. 只在单表 ...

  4. SpringMVC + MyBatis + Mysql + Redis(作为二级缓存) 配置

    2016年03月03日 10:37:47 标签: mysql / redis / mybatis / spring mvc / spring 33805 项目环境: 在SpringMVC + MyBa ...

  5. SpringMVC +Spring + MyBatis + Mysql + Redis(作为二级缓存) 配置

    转载:http://blog.csdn.net/xiadi934/article/details/50786293 项目环境: 在SpringMVC +Spring + MyBatis + MySQL ...

  6. SpringBank 开发日志 Mybatis 使用redis 作为二级缓存时,无法通过cacheEnabled=false 将其关闭

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC ...

  7. mybatis结合redis实战二级缓存(六)

    之前的文章中我们意见分析了一级缓存.二级缓存的相关源码和基本原理,今天我们来分享下了mybatis二级缓存和redis的结合,当然mybatis二级缓存也可以和ehcache.memcache.OSC ...

  8. mybatis结合redis实战二级缓存

    之前的文章中我们意见分析了一级缓存.二级缓存的相关源码和基本原理,今天我们来分享下了mybatis二级缓存和redis的结合,当然mybatis二级缓存也可以和ehcache.memcache.OSC ...

  9. springboot+mybatis 用redis作二级缓存

    1.加入相关依赖包: <?xml version="1.0" encoding="UTF-8"?> <project xmlns=" ...

随机推荐

  1. 2018-8-9-win10-uwp-装机必备应用-含源代码

    title author date CreateTime categories win10 uwp 装机必备应用 含源代码 lindexi 2018-8-9 9:7:31 +0800 2018-8-9 ...

  2. Android7.0 添加快速设定Quick Settings Tile

    Android7.0新推出了一个非常实用的功能--添加快速设定(或者翻译成快速设置),但是感觉社区里关注的人比较少,可能目前为止国内还没有Android7.0的手机,但是越早接触越好,甚至可以告诉产品 ...

  3. python 成员

    一.成员 1.实例变量 对象.属性=xxxx class Person: def __init__(self,name,id,gender,birth): self.name = name self. ...

  4. 【datagrid】动态加载列 2016-01-03 16:32 2013人阅读 评论(19) 收藏

    之前我们的项目在前台显示只需要把数据从数据库读出来进行显示就可以,datagrid的表头字段都是写死的,把数据往表里一扔,就基本没什么事儿了,结果客户前几天要求,其中一个字段不能是死的,应该是有多少项 ...

  5. HDOJ1016 Prime Ring Problem(DFS深层理解)

      Prime Ring Problem                                                                       时间限制: 200 ...

  6. hdu 4629 Burning (扫描线)

    Problem - 4629 以前写过PSLG模拟的版本,今天写了一下扫描线做这题. 其实这题可以用set存线段来做,类似于判断直线交的做法.不过实现起来有点麻烦,于是我就直接暴力求交点了. 代码如下 ...

  7. Android 开源库StickyListHeadersListView来实现ListView列表分组效果

    项目中有一新的需求,要求能像一些Android机带"联系人列表"一样,数据可以自动分组,且在列表滑动过程中,列表头固定在顶部,效果图如下: 下面就带大家实现上面的效果, 首先,我们 ...

  8. Python错误:AttributeError: 'generator' object has no attribute 'next'解决办法

    今天在学习生成器对象(generation object)运行以下代码时,遇到了一个错误: #定义生成器函数def liebiao(): for x in range(10): yield x#函数调 ...

  9. iptables 操作规则

    iptables -nL查看本机关于iptables的设置情况,默认查看的是-t filter,可以指定-t nat iptables-save > iptables.rule会保存当前的防火墙 ...

  10. [kuangbin带你飞]专题九 连通图D - Network POJ - 3694

    这道题其实也非常简单,只是在求割边及其个数的情况下,每次往里面加入新的边,并再次计算割边的个数. 我们用tarjan可以求出原图的桥以及个数,当然我们不能暴力加边,然后求解,那么如何求呢??? 其实非 ...