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>
<!– Hack:确保commons-logging的jar包不被引入,否则将和jcl-over-slf4j冲突 –>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
<scope>provided</scope>
</dependency>
<!– slf4j的实现:logback,用来取代log4j。更快、更强! –>
<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&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" > <!--<!–<--声明全局异常–>-->
<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:\Y2\SMSsptingMVC\target\SMSsptingMVC-1.0-SNAPSHOT\uploadFiles\**"
location="../uploadFiles/" />--> <!--<!–注解驱动的配置–>后面加了转换服务,相当于自动会在文本框获得之后自动装换为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>
<!--<!–解决通过ajax 生成json对象对时间的格式转化–>(在控制器方法直接返回一个对象,然后自动封装成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> <!--<!–配置多视图解析器同上–>-->
<!--<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>-->
<!--<!– 指定 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>--> <!--<!–配置文本框获得的String转化为Date类型 自动转换服务的bean–>-->
<!--<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">-->
<!--<property name="converters">-->
<!--<list>-->
<!--<!–相当于配置此类的参数值,第一个:String 第二个:指定的格式–>-->
<!--<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()的操作。
spring-data-redis集成ehcache实现缓存的更多相关文章
- spring boot通过Spring Data Redis集成redis
在spring boot中,默认集成的redis是Spring Data Redis,Spring Data Redis针对redis提供了非常方便的操作模版RedisTemplate idea中新建 ...
- spring data redis使用1——连接的创建
spring data redis集成了几个Redis客户端框架,Jedis , JRedis (Deprecated since 1.7), SRP (Deprecated since 1.7) a ...
- Spring Data Redis配置项有多少(不列举具体,只提供找的方法)
首先,要说明Spring Data Redis集成了很多款客户端,比如Jedis这些. 而如果在注入Bean时,我们一般是可以设置一些项的,比如hostName和port等,对于这些项一般的查找方式通 ...
- 使用Spring Data Redis操作Redis(单机版)
说明:请注意Spring Data Redis的版本以及Spring的版本!最新版本的Spring Data Redis已经去除Jedis的依赖包,需要自行引入,这个是个坑点.并且会与一些低版本的Sp ...
- (37)Spring Boot集成EHCache实现缓存机制【从零开始学Spring Boot】
[本文章是否对你有用以及是否有好的建议,请留言] 写后感:博主写这么一系列文章也不容易啊,请评论支持下. 如果看过我之前(35)的文章这一篇的文章就会很简单,没有什么挑战性了. 那么我们先说说这一篇文 ...
- Spring Data Redis 让 NoSQL 快如闪电 (1)
[编者按]本文作者为 Xinyu Liu,详细介绍了 Redis 的特性,并辅之以丰富的用例.在本文的第一部分,将重点概述 Redis 的方方面面.文章系国内 ITOM 管理平台 OneAPM 编译呈 ...
- Redis08-击穿&穿透&雪崩&spring data redis
一.常见概念 击穿: 概念:redis作为缓存,设置了key的过期时间,key在过期的时候刚好出现并发访问,直接击穿redis,访问数据库 解决方案:使用setnx() ->相当于一把锁,设置的 ...
- Spring Boot Redis 集成配置(转)
Spring Boot Redis 集成配置 .embody{ padding:10px 10px 10px; margin:0 -20px; border-bottom:solid 1px #ede ...
- spring data redis RedisTemplate操作redis相关用法
http://blog.mkfree.com/posts/515835d1975a30cc561dc35d spring-data-redis API:http://docs.spring.io/sp ...
- spring mvc Spring Data Redis RedisTemplate [转]
http://maven.springframework.org/release/org/springframework/data/spring-data-redis/(spring-data包下载) ...
随机推荐
- 洛谷P1395 会议 题解
$题目$ 为什么这个题会有图论的标签啊,虽然图论也包括找树的重心,可是这很容易让人联想到最短路,但不得不说,这是一个典型的找树的重心模板题. 树的重心是什么? 找到一个点,其所有的子树中最大的子树节点 ...
- 洛谷P1007独木桥题解
题目 这个题看起来很难,但是只要理解了题目,一切都显得简单. 你只需想象出来每个人在碰撞之后仅仅是交换了灵魂, 这样一来,代码就好写了. 附代码: #include<iostream> # ...
- 「NOI2003」逃学的小孩
传送门:>HERE< 题意:给出一棵树(带权),要从一个节点C先走到距离它近的一个节点B,再走到A,要求最坏情况下的总路程(即最长). 解题思路: 乍一看,A,B,C都没给出,这怎么求? ...
- SSL加速卡调研的原因及背景
SSL加速卡调研的原因及背景 SSL加速卡调研的原因及背景 网络信息安全已经成为电子商务和网络信息业发展的一个瓶颈,安全套接层(SSL)协议能较好地解决安全处理问题,而SSL加速器有效地提高了网络安全 ...
- MT【250】距离0-7
是否存在一个正方体,它的8个顶点到某一个平面的距离恰好为$0,1,2,3,4,5,6,7$ ?若存在指出正方体与相应的平面的位置关系.不存在说明理由. 分析:设平面$\alpha$的单位法向量为$\o ...
- Hdoj 2289.Cup 题解
Problem Description The WHU ACM Team has a big cup, with which every member drinks water. Now, we kn ...
- MVC接收列表参数
ASP.NET MVC 表单参数如果有列表时要怎么写呢. 虽然很久不用MVC了,但几乎每次遇到一次就要研究一下.然后又忘了. 其实也明白这是未完全弄清楚表单参数的传递形式,如果明白了,就知道MVC为 ...
- 【dfs】p1731 生日蛋糕
1441:[例题2]生日蛋搞 [题目描述] 7月17日是Mr.W的生日,ACM-THU为此要制作一个体积为Nπ的M层生日蛋糕,每层都是一个圆柱体.设从下往上数第i(1≤i≤M)层蛋糕是半径为Ri, 高 ...
- 【php】 php获取文件路径中的文件名和文件后缀方法
获取文件名 $file = realpath(__DIR__.'/images/common/../addBtn.png'); 方法一 $file = realpath(__DIR__.'/image ...
- 数组拆分I
题目描述 给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最 ...