目的:

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

Mybatis整合ehcache实现二级缓存

  • ssm中整合ehcache

  在POM中导入相关依赖

org.springframework    spring-context-support    ${spring.version}org.mybatis.caches    mybatis-ehcache    1.1.0net.sf.ehcache    ehcache    2.10.0
  • 修改日志配置,因为ehcache使用了Slf4j作为日志输出

  日志我们使用slf4j,并用log4j来实现。SLF4J不同于其他日志类库,与其它有很大的不同。

SLF4J(Simple logging Facade for Java)不是一个真正的日志实现,而是一个抽象层( abstraction layer),

它允许你在后台使用任意一个日志类库。

  Pom.xml

    2.9.13.2.01.7.13org.slf4j      slf4j-api      ${slf4j.version}org.slf4j      jcl-over-slf4j      ${slf4j.version}runtimeorg.apache.logging.log4j      log4j-api      ${log4j2.version}org.apache.logging.log4j      log4j-core      ${log4j2.version}org.apache.logging.log4j      log4j-slf4j-impl      ${log4j2.version}org.apache.logging.log4j      log4j-web      ${log4j2.version}runtimecom.lmax      disruptor      ${log4j2.disruptor.version}

  在Resource中添加一个ehcache.xml的配置文件

  ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>

  在applicationContext-mybatis.xml中给mybatis设置支持

      truefalsetrue

现在我们来测试一下它访问是否使用了二级缓存

@Test    public void cacheSingle() {        Book book= this.bookService.selectByPrimaryKey(5);        System.out.println(book);        Book book2= this.bookService.selectByPrimaryKey(5);        System.out.println(book2);    }

  效果:

很明显查询了两次数据库,没有成功,继续往下看如何解决这个问题

  我们需要在BookMapper.xml中加入chache配置

  我们在运行之前的测试方法测试一下

  很明显,第一次从数据库中查询数据第二次就从缓存中拿数据了

  现在我们来测试查询多条数据的效果

@Test    public void cacheMany() {        Map map = new HashMap();        map.put("bname", StringUtils.toLikeStr("圣墟"));        List hhhh = this.bookService.listPager(map,pageBean);        for (Map m : hhhh) {            System.out.println(m);        }        List hhhh2 = this.bookService.listPager(map,pageBean);        for (Map m : hhhh2) {            System.out.println(m);        }    }

  效果:

  •   关闭缓存

既然开启了那就会有关闭缓存的时候,对吧

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

  

注意:

1、mybatis默认使用的二级缓存框架就是ehcache(org.mybatis.caches.ehcache.EhcacheCache),无缝结合

2、Mybatis缓存开关一旦开启,可缓存单条记录,也可缓存多条,hibernate不能缓存多条。

3、Mapper接口上的所有方法上另外提供关闭缓存的属性


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

  2. 添加jar依赖

    添加redis相关依赖

    2.9.01.7.1.RELEASEredis.clients      jedis      ${redis.version}org.springframework.data      spring-data-redis      ${redis.spring.version}

  log4j2配置

jackson依赖

    2.9.3com.fasterxml.jackson.core      jackson-databind      ${jackson.version}com.fasterxml.jackson.core      jackson-core      ${jackson.version}com.fasterxml.jackson.core      jackson-annotations      ${jackson.version}
  • spring + redis 集成实现缓存功能(与mybatis无关)

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

  redis.properties

redis.hostName=192.168.80.128redis.password=613613redis.timeout=10000redis.maxIdle=300redis.maxTotal=1000redis.maxWaitMillis=1000redis.minEvictableIdleTimeMillis=300000redis.numTestsPerEvictionRun=1024redis.timeBetweenEvictionRunsMillis=30000redis.testOnBorrow=trueredis.testWhileIdle=true

applicationContext-redis.xml

<?xml version="1.0" encoding="UTF-8"?>

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

applicationContext.xml

  <?xml version="1.0" encoding="UTF-8"?>

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

  将redis缓存引入到mybatis中

package com.ht.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 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() {            @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() {            @Override            public Long doInRedis(RedisConnection connection)                    throws DataAccessException {                return connection.dbSize();            }        });        return size.intValue();    }}

  RedisCacheTransfer

package com.ht.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);    }}

  接下来,我们在BookMapper.xml中配置RedisCache缓存

  测试:

 @Test    public void cacheSingle() {        Book book= this.bookService.selectByPrimaryKey(5);        System.out.println(book);        Book book2= this.bookService.selectByPrimaryKey(5);        System.out.println(book2);    }

ehcache使用_Mybatis整合(Redis、Ehcache)实现二级缓存,恕我直言,你不会相关推荐

  1. SpringBoot整合Redis配置MyBatis二级缓存

    目录 写在前面 源码获取 一.MyBatis缓存机制 1.1.一级缓存 1.2.二级缓存 二.集成Redis 2.1.安装Redis 2.2.项目引入Redis 2.2.1.Maven依赖 2.2.2 ...

  2. Springboot:整合redis对接口数据进行缓存

    文章目录 Springboot:整合redis对接口数据进行缓存 一.注解及其属性介绍 @Cacheable @CacheEvict @CachePut @CacheConfig 二.代码实现 1.创 ...

  3. @primary注解_springboot整合redis分别实现手动缓存和注解缓存

    一.前期准备 1.一个构建好的springboot系统2.下载redis安装包,去redis官网下载3.启动redis服务,windows下双击bin目录下的redis-service.exe 二.环 ...

  4. springboot整合redis分别实现手动缓存和注解缓存

    一.前期准备 一个构建好的springboot系统 下载redis安装包,去redis官网下载 启动redis服务,windows下双击bin目录下的redis-service.exe 二.环境构建 ...

  5. 【MyBatis框架】查询缓存-二级缓存-整合ehcache

    mybatis整合ehcache ehcache是一个分布式缓存框架. 1.分布缓存 我们系统为了提高系统并发,性能.一般对系统进行分布式部署(集群部署方式) 如图 不使用分布缓存,缓存的数据在各各服 ...

  6. Hibernate EHCache - Hibernate二级缓存

    Hibernate EHCache - Hibernate二级缓存 欢迎使用Hibernate二级缓存示例教程.今天我们将研究Hibernate EHCache,它是最受欢迎的Hibernate二级缓 ...

  7. spring boot集成ehcache 2.x 用于hibernate二级缓存

    spring boot集成ehcache 2x 用于hibernate二级缓存 项目依赖 Ehcache简介 hibernate二级缓存配置 ehcache配置文件 ehcache事件监听 注解方式使 ...

  8. 项目整合一级缓存和二级缓存

    Redis+ehCache实现两级缓存 spring boot中集成了spring cache,并有多种缓存方式的实现,如:Redis.Caffeine.JCache.EhCache等等.但如果只用一 ...

  9. Spring Boot之基于Redis实现MyBatis查询缓存解决方案

    转载自 Spring Boot之基于Redis实现MyBatis查询缓存解决方案 1. 前言 MyBatis是Java中常用的数据层ORM框架,笔者目前在实际的开发中,也在使用MyBatis.本文主要 ...

最新文章

  1. 搜索业务增速下滑 Google廉颇老矣?
  2. python signal模块作用_如何理解python中信号Signal?
  3. c语言两个浮点数相加_C语言中两个浮点数或双精度数的模数
  4. Tomcat启动项目没问题,网页一片空白
  5. java.lang.NoClassDefFoundError: org/apache/http/ssl/TrustStrategy 错误解决办法
  6. 为什么python不需要编译_为什么我用Go写机器学习部署平台,而偏偏不用Python?...
  7. visual studio怎么用_自从用了敏捷,天天在开会?4大Scrum会议如何才能有意义?...
  8. vs窗体程序常用工具_Visual Studio 2010(VS)--消消乐定制版①
  9. CCF-相反数(C语言)
  10. yolov5环境配置及训练coco128数据集
  11. tcl文件调用c语言,TCL与c/c++的互相调用
  12. 富途出海淘金:泡沫翻涌 焦虑不止
  13. 洛谷P4568 [JLOI2011] 飞行路线 题解
  14. 分别用marquee和div+js实现首尾相连循环滚动效果
  15. 软件测试面试题之用例设计题
  16. 痞子衡嵌入式:语音处理工具Jays-PySPEECH诞生记(3)- 音频显示实现(Matplotlib, NumPy1.15.0)...
  17. Outlook如何修复.pst数据文件?
  18. 电脑录屏软件哪个免费
  19. 累死你的不是工作,而是工作方法
  20. Android自定义视频录制

热门文章

  1. 练习图200例图纸讲解_【宅家数学课23】经典微课6:苏教版六年级下册比例尺典型例题选讲及练习(含答案)...
  2. python支持向量机_支持向量机(SVM)Python实现
  3. Halcon算子学习:find_surface_model
  4. QT学习笔记(二):QT MinGW 和 MSVC 编译方式
  5. Python搭建web服务器
  6. 脏读、不可重复读和幻读
  7. Html如何触发闹铃,事件闹钟设置.html
  8. 银行界加强计算机病毒管理,银行计算机管理系统维护现状与对策研究(7.12).doc...
  9. CentOS 7 防火墙命令
  10. 高中学生计算机软件,中学生计算器