spring-data-redis集成ehcache实现缓存

1.结构

2.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <packaging>war</packaging>

  <name>gameCard</name>
  <groupId>SSM</groupId>
  <artifactId>gameCard</artifactId>
  <version>1.0-SNAPSHOT</version>


  <dependencies>
    <!--dependency>
      <groupId>SSM</groupId>
      <artifactId>[the artifact id of the block to be mounted]</artifactId>
      <version>1.0-SNAPSHOT</version>
    </dependency-->
    <!--数据源-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.4</version>
    </dependency>
    <dependency><!--1.c3p0-->
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>
    <dependency><!--2.alibaba-->
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.41</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!--log4j-->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.6.1</version>
    </dependency>
    <!-- 将现有的jakarta commons logging的调用转换成lsf4j的调用。 -->
   <!-- <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jcl-over-slf4j</artifactId>
      <version>1.6.1</version>
    </dependency>
    &lt;!&ndash; Hack:确保commons-logging的jar包不被引入,否则将和jcl-over-slf4j冲突 &ndash;&gt;
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.1.1</version>
      <scope>provided</scope>
    </dependency>
    &lt;!&ndash; slf4j的实现:logback,用来取代log4j。更快、更强! &ndash;&gt;
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>0.9.24</version>
      <scope>runtime</scope>
    </dependency>-->

    <!--实现文件上传-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>

    <!-- spring-webmvc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.12.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.12.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.12.RELEASE</version>
    </dependency>
    <!--mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.5</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>

    <!--mySQL-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.44</version>
    </dependency>

    <!--声明式事务-->
    <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.8</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.directory.studio/org.apache.commons.lang -->
    <dependency>
      <groupId>org.apache.directory.studio</groupId>
      <artifactId>org.apache.commons.lang</artifactId>
      <version>2.6</version>
    </dependency>

    <!-- spring-redis实现 -->
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
      <version>1.6.2.RELEASE</version>
    </dependency>
    <!--redis缓存,不抛redis异常不用加这个依赖包-->
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.9.0</version>
    </dependency>
    <!-- Ehcache实现,用于参考 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-ehcache</artifactId>
      <version>1.0.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jdbc -->
    <!--<dependency>
      <groupId>org.apache.tomcat</groupId>
      <artifactId>tomcat-jdbc</artifactId>
      <version>9.0.8</version>
    </dependency>-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.5</version>
    </dependency>

  </dependencies>

</project>

3.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:p="http://www.springframework.org/schema/p"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
    http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.1.xsd
    http://www.springframework.org/schema/mvc
   http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
    http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"
        default-autowire="byName"   >


  <!-- 自动扫描 -->
  <context:component-scan base-package="cn.jbit" />
  <!-- 引入配置文件 -->
  <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
      <list>
        <value>classpath:db.properties</value>
        <value>classpath:redis.properties</value>
      </list>
    </property>
  </bean>

  <!--数据源,读取数据配置文件-->
  <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="classpath:db.properties"/>
  </bean>
  <!--数据源,C3p0-->
 <!-- <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="jdbcUrl" value="${DB_URL}"/>
    <property name="driverClass" value="${DB_DRIVER}"/>
    <property name="user" value="${DB_NAME}"/>
    <property name="password" value="${DB_PWD}"/>
    <property name="maxPoolSize" value="${DB_MAXConnectionSize}" />
    <property name="maxStatementsPerConnection" value="${DB_MAXActive}"/>
  </bean>-->
  <!--数据源,阿里巴巴-->
  <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="url" value="jdbc:mysql://localhost:3306/gameCard?useUnicode=true&amp;characterEncoding=utf-8" />
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="username" value="${DB_NAME}" />
    <property name="password" value="${DB_PWD}" />
    <property name="maxPoolPreparedStatementPerConnectionSize" value="100"/>
    <property name="maxActive" value="50" />
  </bean>
  <!--会话工厂-->
  <bean name="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="typeAliasesPackage" value="cn.jbit.entity" /><!--实体类别名-->
    <property name="mapperLocations" value="classpath:xml/*.xml"/><!--读取映射文件-->
  </bean>


  <!--扫入日志类-->
  <bean id="log4j" class="cn.jbit.util.Log4j"></bean>
  <!--启用对@AspectJ注解的支持-->
  <aop:aspectj-autoproxy proxy-target-class="true"/>
  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
  </bean>
  <!--声明式事务-->
  <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
      <tx:method name="add*" propagation="REQUIRED" read-only="false"/>
      <tx:method name="update*" propagation="REQUIRED"/>
      <tx:method name="delete*" propagation="REQUIRED" />
     <!-- <tx:method name="find*" propagation="NOT_SUPPORTED" read-only="true"/>
      <tx:method name="search*" propagation="NOT_SUPPORTED" read-only="true" />
      <tx:method name="query*" propagation="NOT_SUPPORTED" read-only="true" />-->
    </tx:attributes>
  </tx:advice>
  <aop:config>
    <aop:pointcut id="pointcut" expression="execution(* cn.jbit.biz..*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
    <aop:aspect ref="log4j" >
      <aop:before method="before" pointcut-ref="pointcut"></aop:before>
      <aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"></aop:after-returning>
      <aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="e"/>
    </aop:aspect>
  </aop:config>



  <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="cn.jbit.dao" />
    <property name="sqlSessionFactoryBeanName" value="sessionFactory"></property>
  </bean>

  <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->

  <tx:annotation-driven transaction-manager="transactionManager" />
  <!-- redis数据源 -->
  <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
    <property name="maxIdle" value="${redis.maxIdle}" />
    <property name="maxTotal" value="${redis.maxActive}" />
    <property name="maxWaitMillis" value="${redis.maxWait}" />
    <property name="testOnBorrow" value="${redis.testOnBorrow}" />
  </bean>
  <!-- Spring-redis连接池管理工厂 -->
  <bean id="jedisConnectionFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
        p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.password}"
        p:pool-config-ref="poolConfig" />
  <!-- 使用中间类解决RedisCache.jedisConnectionFactory的静态注入,从而使MyBatis实现第三方缓存 -->
  <bean id="redisCacheTransfer" class="cn.jbit.cache.RedisCacheTransfer">
    <property name="jedisConnectionFactory" ref="jedisConnectionFactory"/>
  </bean>
</beans>

4.springmvc-servlet.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:p="http://www.springframework.org/schema/p"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
   http://www.springframework.org/schema/aop
   http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
    http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.1.xsd
    http://www.springframework.org/schema/mvc
   http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
    http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"
        default-autowire="byName" >



    <!--&lt;!&ndash;<&#45;&#45;声明全局异常&ndash;&gt;-->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings" >
            <props>
                <!--error为抛出到的jsp文件试图名字-->
                <prop key="RuntimeExeception">error</prop>
            </props>
        </property>
    </bean>

    <!--上传图片的试图解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxInMemorySize" value="50000000"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>


    <!--放过的指定的文件,不用拦截-->
    <mvc:resources mapping="/static/**" location="/WEB-INF/static/" />
    <!--<mvc:resources mapping="/images/**" location="/WEB-INF/images/" />
    <mvc:resources mapping="/js/**" location="/WEB-INF/js/" />
    <mvc:resources mapping="/calendar/**" location="/WEB-INF/calendar/" />
    <mvc:resources mapping="/picture/**" location="/WEB-INF/picture/" />-->
    <!--<mvc:resources mapping="E:Y2SMSsptingMVC	argetSMSsptingMVC-1.0-SNAPSHOTuploadFiles**"
                   location="../uploadFiles/" />-->

    <!--&lt;!&ndash;注解驱动的配置&ndash;&gt;后面加了转换服务,相当于自动会在文本框获得之后自动装换为date类型,-->
    <mvc:annotation-driven>
        <!--//设置json解析的中文,全局防止乱码,不用每个设置produces = {"application/json;charset=utf-8"}-->
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
            <!--&lt;!&ndash;解决通过ajax 生成json对象对时间的格式转化&ndash;&gt;(在控制器方法直接返回一个对象,然后自动封装成json对象)-->
            <!--换掉Jackson最主要的原因是Jackson在处理对象之前的循环嵌套关系时不便。
ps:什么是对象间的循环嵌套?比如A有一个List<B>,B对象里又有一个A对象,当然返回A对象
的Json字符串时,如果是 Jackson就会发生异常,因为Jackson天生不具备处理这种关系的能力,而Fastjson正好具备了这种能力-->
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json</value>
                    </list>
                </property>
                <property name="features"><!--Fastjson的SerializerFeature序列化属性-->
                    <list>
                        <!--输出的date日期转化器-->
                        <value>WriteDateUseDateFormat</value><!--全局修改日期格式,默认为false-->
                        <!--<value>WriteMapNullValue</value>--><!--是否输出值为null的字段,默认为false-->
                        <!-- <value>QuoteFieldNames</value>--><!--输出key时是否使用双引号,默认为true-->
                    </list>
                </property>
            </bean>

        </mvc:message-converters>
    </mvc:annotation-driven>

    <!--配置多视图解析器,允许同样的内容数据呈现不同的view-->
    <!-- 多视图解析器 -->
    <!-- 多视图解析器 -->
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
        <!-- 指定json 用什么工具解析  xml 用什么工具解析 -->
        <!--<property name="defaultViews">-->
        <!--<list>-->
        <!--<bean class="com.alibaba.fastjson.support.spring.FastJsonJsonView">-->
        <!--<property name="charset" value="UTF-8"/>-->
        <!--</bean>-->
        <!--<bean class="org.springframework.web.servlet.view.xml.MarshallingView">-->
        <!--<constructor-arg>-->
        <!--<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">-->
        <!--<property name="classesToBeBound">-->
        <!--<list>-->
        <!--<value>cn.jbit.smbms.entity.Message</value>-->
        <!--</list>-->
        <!--</property>-->
        <!--</bean>-->
        <!--</constructor-arg>-->
        <!--</bean>-->
        <!--</list>-->
        <!--</property>-->
        <!-- 指定 jsp解析器  视图解析器 控制器返回字符串 查找相应后缀的页面-->
        <property name="viewResolvers">
            <list>
                <bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="prefix" value="/WEB-INF/jsp/" />
                    <property name="suffix" value=".jsp" />
                </bean>
            </list>
        </property>
    </bean>

    <!--&lt;!&ndash;配置多视图解析器同上&ndash;&gt;-->
    <!--<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">-->
    <!--<property name="favorParameter" value="true"/>-->
    <!--<property name="defaultViews" value="text/html"/>-->
    <!--<property name="mediaTypes">-->
    <!--<map>-->
    <!--<entry key="html" value="text/html;charset=UTF-8"/>-->
    <!--<entry key="json" value="application/json;charset=UTF-8"/>-->
    <!--<entry key="xml" value="application/xml;charset=UTF-8"/>-->
    <!--</map>-->
    <!--</property>-->
    <!--&lt;!&ndash; 指定 jsp解析器  视图解析器&ndash;&gt;-->
    <!--<property name="viewResolvers">-->
    <!--<list>-->
    <!--<bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
    <!--<property name="prefix" value="/WEB-INF/jsp/" />-->
    <!--<property name="suffix" value=".jsp" />-->
    <!--</bean>-->
    <!--</list>-->
    <!--</property>-->
    <!--</bean>-->

    <!--&lt;!&ndash;配置文本框获得的String转化为Date类型  自动转换服务的bean&ndash;&gt;-->
    <!--<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">-->
    <!--<property name="converters">-->
    <!--<list>-->
    <!--&lt;!&ndash;相当于配置此类的参数值,第一个:String 第二个:指定的格式&ndash;&gt;-->
    <!--<bean class="cn.jbit.smbms.util.StringToDateConvert">-->
    <!--<constructor-arg type="java.lang.String" value="yyyy-MM-dd"/>-->
    <!--</bean>-->
    <!--</list>-->
    <!--</property>-->
    <!--</bean>-->

    <!--配置全局系统拦截器-->
    <mvc:interceptors>
    <mvc:interceptor>
        <!-- 进行拦截:/**表示拦截所有controller -->
        <mvc:mapping path="/**" />
    <bean class="cn.jbit.util.Interceptor"/>
    </mvc:interceptor>
    </mvc:interceptors>

    <!--扫描注解的bean-->
    <context:component-scan base-package="cn.jbit.biz,cn.jbit.biz.bizImpl,cn.jbit.control,cn.jbit.cache" />
</beans>

5.mybatis-cache.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
   <!-- 配置mybatis的缓存,延迟加载等等一系列属性 -->
   <settings>

      <!-- 全局映射器启用缓存 -->
      <setting name="cacheEnabled" value="true" />

      <!-- 查询时,关闭关联对象即时加载以提高性能 -->
      <setting name="lazyLoadingEnabled" value="false" />

      <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
      <setting name="multipleResultSetsEnabled" value="true" />

      <!-- 允许使用列标签代替列名 -->
      <setting name="useColumnLabel" value="true" />

      <!-- 不允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->
      <setting name="useGeneratedKeys" value="false" />

      <!-- 给予被嵌套的resultMap以字段-属性的映射支持 FULL,PARTIAL -->
      <setting name="autoMappingBehavior" value="PARTIAL" />

      <!-- 对于批量更新操作缓存SQL以提高性能 BATCH,SIMPLE -->
       <setting name="defaultExecutorType" value="BATCH" />

      <!-- 数据库超过25000秒仍未响应则超时 -->
      <!-- <setting name="defaultStatementTimeout" value="25000" /> -->

      <!-- Allows using RowBounds on nested statements -->
      <setting name="safeRowBoundsEnabled" value="false" />

      <!-- Enables automatic mapping from classic database column names A_COLUMN 
         to camel case classic Java property names aColumn. -->
      <setting name="mapUnderscoreToCamelCase" value="true" />

      <!-- MyBatis uses local cache to prevent circular references and speed 
         up repeated nested queries. By default (SESSION) all queries executed during 
         a session are cached. If localCacheScope=STATEMENT local session will be 
         used just for statement execution, no data will be shared between two different 
         calls to the same SqlSession. -->
      <setting name="localCacheScope" value="SESSION" />

      <!-- Specifies the JDBC type for null values when no specific JDBC type 
         was provided for the parameter. Some drivers require specifying the column 
         JDBC type but others work with generic values like NULL, VARCHAR or OTHER. -->
      <setting name="jdbcTypeForNull" value="OTHER" />

      <!-- Specifies which Object's methods trigger a lazy load -->
      <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString" />

      <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 -->
      <setting name="aggressiveLazyLoading" value="true" />

   </settings>

</configuration>

6.cache

package cn.jbit.cache;

import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;

public class RedisCacheTransfer {

    public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
        RedisCache.setJedisConnectionFactory(jedisConnectionFactory);
    }
}

package cn.jbit.cache;

import cn.jbit.util.MD5;
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import redis.clients.jedis.exceptions.JedisConnectionException;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class RedisCache implements Cache {

   private static JedisConnectionFactory jedisConnectionFactory;

   private final String id;

   /**
    * The {@code ReadWriteLock}.
    */
   private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

   public RedisCache(final String id) {
      if (id == null) {
         throw new IllegalArgumentException("Cache instances require an ID");
      }
      System.out.println(">>>>>>>>>>>>>>>>>>>>>MybatisRedisCache:id=" + id);
      this.id = id;
   }


   public void clear() {
      JedisConnection connection = null;
      try {
         connection = jedisConnectionFactory.getConnection();
         connection.flushDb();
         connection.flushAll();
         System.out.println("clear=redis======>");
      } catch (JedisConnectionException e) {
         e.printStackTrace();
      } finally {
         if (connection != null) {
            connection.close();
         }
      }
   }


   public String getId() {
      return this.id;
   }


   public Object getObject(Object key) {
      Object result = null;
      JedisConnection connection = null;
      try {
         key = MD5.getMD5Str(key.toString());
         connection = jedisConnectionFactory.getConnection();
         RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
         result = serializer.deserialize(connection.get(serializer.serialize(key)));
         if (result == null) {
            removeObject(key);
            return null;
         }
         System.out.println("get-Redis-----key=:" + key);
      } catch (JedisConnectionException e) {
         e.printStackTrace();
      } finally {
         if (connection != null) {
            connection.close();
         }
      }
      return result;
   }


   public ReadWriteLock getReadWriteLock() {
      return this.readWriteLock;
   }


   public int getSize() {
      int result = 0;
      JedisConnection connection = null;
      try {
         connection = jedisConnectionFactory.getConnection();
         result = Integer.valueOf(connection.dbSize().toString());
         System.out.println(this.id + "---->>>>getSize:" + result);
      } catch (JedisConnectionException e) {
         e.printStackTrace();
      } finally {
         if (connection != null) {
            connection.close();
         }
      }
      return result;
   }


   public void putObject(Object key, Object value) {
      if (value.toString().equals("[]")) {
         System.out.println("key:="+key+"--- value=:" + value);
         return;
      }
      JedisConnection connection = null;
      try {
         RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
         key = MD5.getMD5Str(key.toString());
         connection = jedisConnectionFactory.getConnection();
         connection.set(serializer.serialize(key), serializer.serialize(value));
         System.out.println("rdis-put--------key:=" + key + "  value:=" + value);
      } catch (JedisConnectionException e) {
         e.printStackTrace();
      } finally {
         if (connection != null) {
            connection.close();
         }
      }
   }


   public Object removeObject(Object key) {
      JedisConnection connection = null;
      Object result = null;
      try {
         key = MD5.getMD5Str(key.toString());
         connection = jedisConnectionFactory.getConnection();
         RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
         result = connection.expire(serializer.serialize(key), 0);
         System.out.println("remove-Redis-----" + this.id + " key" + key);
      } catch (JedisConnectionException e) {
         e.printStackTrace();
      } finally {
         if (connection != null) {
            connection.close();
         }
      }
      return result;
   }

   public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
      RedisCache.jedisConnectionFactory = jedisConnectionFactory;
   }

}

7.调用在mapper.xml中加入:<cache eviction="LRU" type="cn.jbit.cache.RedisCache"/>

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.jbit.dao.CardsDao"><!--指定对应得dao层-->
    <cache eviction="LRU" type="cn.jbit.cache.RedisCache"/>

    <select id="searchList" resultType="Cards">
        SELECT c.*,g.`gid` AS gid,g.`gName` AS  gName
        FROM `cards` AS c JOIN `gameOrCard` AS ga ON c.cid=ga.cid
        JOIN `games` AS g ON g.`gid`=ga.`gid`
        JOIN `gamestype` AS ty ON g.`tId`=ty.`tId`
        <where>
            <if test="tid>0">AND g.`tid`=#{tid}</if>
            <if test="gid>0">AND g.`gid`=#{gid}</if>
            <if test="searchInfo != null and searchInfo != ''">
                AND CONCAT_WS(
               c.`cName`,g.`gName`,c.`iniPrice`,ty.`tName`
                )LIKE CONCAT('%',#{searchInfo},'%')
            </if>
        </where>
        AND c.isShelves=0 and c.`number`>0 ORDER BY g.gid,c.price,c.iniPrice
        limit #{index},#{pagesize}
    </select>

    <select id="getcount" resultType="Integer">
        SELECT COUNT(1)
        FROM `cards` AS c JOIN `gameOrCard` AS ga ON c.cid=ga.cid
        JOIN `games` AS g ON g.`gid`=ga.`gid`
        JOIN `gamestype` AS ty ON g.`tId`=ty.`tId`
        <where>
            <if test="tid>0">AND g.`tid`=#{tid}</if>
            <if test="gid>0">AND g.`gid`=#{gid}</if>
            <if test="searchInfo != null and searchInfo != ''">
                AND CONCAT_WS(
                c.`cName`,g.`gName`,c.`iniPrice`,ty.`tName`
                )LIKE CONCAT('%',#{searchInfo},'%')
            </if>
        </where>
        AND c.isShelves=0 and c.`number`>0
    </select>

    <select id="searchNewTime" resultType="Cards">
        SELECT * FROM cards  WHERE isShelves=0  and `number`>0 ORDER BY upTime DESC LIMIT 0,#{top}
    </select>

    <select id="searchByInfo" parameterType="Cards" resultType="Cards">
        SELECT c.*,g.`gid` AS gid,g.`gName` AS  gName
        FROM `cards` AS c JOIN `gameOrCard` AS ga ON c.cid=ga.cid
        JOIN `games` AS g ON g.`gid`=ga.`gid`
          <where>
              <if test="cId>0">and c.`cId`=#{cId}</if>
              <if test="gid>0">and g.`gid`=#{gid}</if>
          </where>
    </select>

    <select id="searchById" resultType="Cards">
        SELECT * FROM `cards`
        WHERE `cId`=#{cId}
    </select>

    <update id="updateCards" parameterType="Cards">
        UPDATE `cards`
        <set>
            <if test="titleImg != null">`titleImg`=#{titleImg},</if>
            <if test="cInfo != null">`cInfo`=#{cInfo},</if>
            <if test="iniPrice>0">`iniPrice`=#{iniPrice},</if>
            <if test="price>0">`price`=#{price},</if>
            <if test="praiseRate>0">`praiseRate`=#{praiseRate},</if>
            <if test="isShelves>-1">`isShelves`=#{isShelves},</if>
            <if test="number>-1">`number`=#{number},</if>
            <if test="version>-1">`version`=#{version}+1,</if>
        </set>
        WHERE `cId`=#{cId} AND `version`=#{version} and `number`>0
    </update>
</mapper>

8.测试:

后台

前台:


可以看出数据是从后台redis缓存中读取,并且少了很多人工getKey(),setKey()的操作。




原文地址:https://www.cnblogs.com/zeussbook/p/9297077.html