mybatis整合Redis和ehcache实现二级缓存

目录:

mybatis整合ehcache
mybatis整合Redis

我们知道mybatis的整合和hibernate没多大区别,原理大部分都是一样的

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>


2、然后我们需要修改日志配置,因为ehcache使用了Slf4j作为日志输出

日志所需的pom依赖

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



3、在Resources中添加配置文件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>


4、然后我们是与mybatis整合的,所以在applicationContext-mybatis.xml中加入ehcache的配置

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



applicationContext-mybatis.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">
    <!--1. 注解式开发 -->
    <!-- 注解驱动 -->
    <context:annotation-config/>
    <!-- 用注解方式注入bean,并指定查找范围:com.cgl.ssm及子子孙孙包-->
    <context:component-scan base-package="com.liuxia"/>

    <!--<context:property-placeholder location="classpath:jdbc.properties"/>
-->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!--初始连接数-->
        <property name="initialSize" value="10"/>
        <!--最大活动连接数-->
        <property name="maxTotal" value="100"/>
        <!--最大空闲连接数-->
        <property name="maxIdle" value="50"/>
        <!--最小空闲连接数-->
        <property name="minIdle" value="10"/>
        <!--设置为-1时,如果没有可用连接,连接池会一直无限期等待,直到获取到连接为止。-->
        <!--如果设置为N(毫秒),则连接池会等待N毫秒,等待不到,则抛出异常-->
        <property name="maxWaitMillis" value="-1"/>
    </bean>

    <!--4. spring和MyBatis整合 -->
    <!--1) 创建sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定数据源 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 自动扫描XxxMapping.xml文件,**任意路径 -->
        <property name="mapperLocations" value="classpath*:com/liuxia/**/mapper/*.xml"/>
        <!-- 指定别名 -->
       <!-- <property name="typeAliasesPackage" value="com/liuxia/**/model"/>-->
        <!--设置mybaits对缓存的支持-->
        <property name="configurationProperties">
            <props>
                <!-- 全局映射器启用缓存 *主要将此属性设置完成即可-->
                <prop key="cacheEnabled">true</prop>
                <!-- 查询时,关闭关联对象即时加载以提高性能 -->
                <prop key="lazyLoadingEnabled">false</prop>
                <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 -->
                <prop key="aggressiveLazyLoading">true</prop>
            </props>
        </property>
        <!--配置pagehelper插件-->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <value>
                            helperDialect=mysql
                        </value>
                    </property>
                </bean>
            </array>
        </property>
    </bean>

    <!--2) 自动扫描com/cgl/ssm/**/mapper下的所有XxxMapper接口(其实就是DAO接口),并实现这些接口,-->
    <!--   即可直接在程序中使用dao接口,不用再获取sqlsession对象-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--basePackage 属性是映射器接口文件的包路径。-->
        <!--你可以使用分号或逗号 作为分隔符设置多于一个的包路径-->
        <property name="basePackage" value="com/liuxia/**/mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager" />
    <aop:aspectj-autoproxy/>
</beans>


5、然后我们的Mapper映射的xml中开启二级缓存,这里是BookMapper.xml
加在mapper标签下面第一个即可


 <!--配置ehcache-->
  <cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>

然后我们还能改变useCache的值来开启和关闭缓存


<select id="selectByPrimaryKey" useCache="true" resultMap="BaseResultMap" parameterType="java.lang.Integer" >

然后我们一样用JUnit测试一个方法查询同一个数据,开启了后通过日志看到第二次没有执行sql语句了,而是进入缓存取的值

   @Test
        public void testCacheOne() {
            Book b = this.bookService.selectByPrimaryKey(15);
            System.out.println(b);
            System.out.println(b);
        }



在这里插入图片描述
这样整合ehcache就算是成功了

mybatis整合Redis

ehcache直接在jvm虚拟机中缓存,速度快,效率高;但是缓存共享麻烦,集群分布式应用不方便
redis是通过socket访问到缓存服务,效率比ecache低,比数据库要快很多,处理集群和分布式缓存方便,有成熟的方案

1、首先依然是导入整合所需pom依赖

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

log4j和序列化需要的jackson


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



2、因为redis是NoSql(非关系型数据库),所以需要我们的连接文件,然后把redis.properties导入

redis.hostName=192.168.137.129
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.xml文件,因为我们需要在文件中引入我们redis.properties文件又要引入jdbc.properties文件,还有我们桥接redis的工具类 所以需要在我们的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">

<!--整合mybatis框架-->
    <context:property-placeholder location="classpath:jdbc.properties,classpath:redis.properties"/>
   <import resource="applicationContext-mybatis.xml"></import>

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

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

桥接的工具类 RedisCache


package com.liuxia.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注入到工具类中去

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



4、然后我们就在Mapper.xml中添加开启缓存的配置, 这配置的就是我们的桥接工具类,ehcache配置的是jar包自带的桥接类

<cache type="com.liuxia.util.RedisCache"></cache>

5、把实体类实现序列化,implements Serializable
然后我们就可以去用JUnit测试了,和一样是刚刚那个方法,只不过用的缓存不同,这次它调用的就是redis的缓存了

在这里插入图片描述
我们还可以在redis里面看见我们查询的数据,我们设定了存储时间位一分钟,也就是一分钟后数据就自动删除了
在这里插入图片描述
拜拜啦

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值