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;<--声明全局异常&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:\Y2\SMSsptingMVC\target\SMSsptingMVC-1.0-SNAPSHOT\uploadFiles\**"
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()的操作。

spring-data-redis集成ehcache实现缓存的更多相关文章

  1. spring boot通过Spring Data Redis集成redis

    在spring boot中,默认集成的redis是Spring Data Redis,Spring Data Redis针对redis提供了非常方便的操作模版RedisTemplate idea中新建 ...

  2. spring data redis使用1——连接的创建

    spring data redis集成了几个Redis客户端框架,Jedis , JRedis (Deprecated since 1.7), SRP (Deprecated since 1.7) a ...

  3. Spring Data Redis配置项有多少(不列举具体,只提供找的方法)

    首先,要说明Spring Data Redis集成了很多款客户端,比如Jedis这些. 而如果在注入Bean时,我们一般是可以设置一些项的,比如hostName和port等,对于这些项一般的查找方式通 ...

  4. 使用Spring Data Redis操作Redis(单机版)

    说明:请注意Spring Data Redis的版本以及Spring的版本!最新版本的Spring Data Redis已经去除Jedis的依赖包,需要自行引入,这个是个坑点.并且会与一些低版本的Sp ...

  5. (37)Spring Boot集成EHCache实现缓存机制【从零开始学Spring Boot】

    [本文章是否对你有用以及是否有好的建议,请留言] 写后感:博主写这么一系列文章也不容易啊,请评论支持下. 如果看过我之前(35)的文章这一篇的文章就会很简单,没有什么挑战性了. 那么我们先说说这一篇文 ...

  6. Spring Data Redis 让 NoSQL 快如闪电 (1)

    [编者按]本文作者为 Xinyu Liu,详细介绍了 Redis 的特性,并辅之以丰富的用例.在本文的第一部分,将重点概述 Redis 的方方面面.文章系国内 ITOM 管理平台 OneAPM 编译呈 ...

  7. Redis08-击穿&穿透&雪崩&spring data redis

    一.常见概念 击穿: 概念:redis作为缓存,设置了key的过期时间,key在过期的时候刚好出现并发访问,直接击穿redis,访问数据库 解决方案:使用setnx() ->相当于一把锁,设置的 ...

  8. Spring Boot Redis 集成配置(转)

    Spring Boot Redis 集成配置 .embody{ padding:10px 10px 10px; margin:0 -20px; border-bottom:solid 1px #ede ...

  9. spring data redis RedisTemplate操作redis相关用法

    http://blog.mkfree.com/posts/515835d1975a30cc561dc35d spring-data-redis API:http://docs.spring.io/sp ...

  10. spring mvc Spring Data Redis RedisTemplate [转]

    http://maven.springframework.org/release/org/springframework/data/spring-data-redis/(spring-data包下载) ...

随机推荐

  1. scrapy爬取知乎问答

    登陆 参考 https://github.com/zkqiang/Zhihu-Login # -*- coding: utf-8 -*- import scrapy import time impor ...

  2. 机器学习---朴素贝叶斯分类器(Machine Learning Naive Bayes Classifier)

    朴素贝叶斯分类器是一组简单快速的分类算法.网上已经有很多文章介绍,比如这篇写得比较好:https://blog.csdn.net/sinat_36246371/article/details/6014 ...

  3. 【XSY1642】Another Boring Problem 树上莫队

    题目大意 给你一棵\(n\)个点的树,每个点有一个颜色\(c_i\),每次给你\(x,y,k\),求从\(x\)到\(y\)的路径上出现次数第\(k\)多的颜色的出现次数 \(n,q\leq 1000 ...

  4. composer阿里云短信服务不支持传参为数值--为2017年短信接口,2018阿里云有更新http://www.cnblogs.com/q1104460935/p/8916096.html

    composer 阿里云短信服务使用 xuying/aliyun_mns     更新到2017年初,不再更新 ){;, ); }; } ; }; }; }} 以下为发送成功返回对象 object(A ...

  5. Codeforces Round #449 (Div. 1) Willem, Chtholly and Seniorious (ODT维护)

    题意 给你一个长为 \(n\) 的序列 \(a_i\) 需要支持四个操作. \(1~l~r~x:\) 把 \(i \in [l, r]\) 的 \(a_i\) 加 \(x\) . \(2~l~r~x: ...

  6. 自学Linux命令行与Shell脚本之路

    自学Linux命令行与Shell脚本之路[第一回]:初识Linux   1.1 自学Linux Shell1.1-Linux初识 1.2 自学Linux Shell1.2-Linux目录结构 1.3  ...

  7. kafka问题集锦

    一. org.apache.kafka.common.errors.TimeoutException: Batch Expired 问题描述:通过java客户端访问kafka服务器,当生产者线程向ka ...

  8. 牛客小白月赛12 F 华华开始学信息学 (分块+树状数组)

    链接:https://ac.nowcoder.com/acm/contest/392/F来源:牛客网 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 32768K,其他语言65536K ...

  9. mfc01

    1.解决不能将参数1从“const char []”转换为“LPCTSTR” ,使用多字节字符集.

  10. Mock2 moco框架的http协议get方法Mock的实现

    首先在Chapter7文件夹下再新建一个startGet.json startget.json代码如下,因为是get请求,所以要写method关键字,有两个,一个是有参数,一个是无参数的请求. [ { ...