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. 洛谷p1091合唱队形题解

    题目 合唱队形首先要满足的是从1这个位置到中间任意的位置为单增的,从中间任意的位置到最后是单减的,且长度最长.这样才能满足出列的同学最少. 如果要满足这个条件那么我们可以先预处理出每个点的从前找的最长 ...

  2. 为何在新线程中使用注解获取不到Spring管理的Bean

    新建的线程类NewThread,在这个类中国使用Spring的注解获取Service,为null 网上已有这种问题的解决方案,但是为何在新线程中使用注解获取不到Spring管理的Bean? 问了老大, ...

  3. Linux查看实时网卡流量的几种方式

    Linux查看实时网卡流量的几种方式 来源  https://www.jianshu.com/p/b9e942f3682c 在工作中,我们经常需要查看服务器的实时网卡流量.通常,我们会通过这几种方式查 ...

  4. JumpServer 跳板机系统

    Jumpserver项目为开源项目,截至到目前最新版本为4.0,4.0功能并不完整,无上传.下载功能,配置复杂.启动服务也较繁琐,推荐使用0.3.2版本,文档较全,安装简单文档链接https://gi ...

  5. windows 路由转发

    netsh interface ipv6 install 将内网的2433端口转发到外网的11111端口netsh interface portproxy add v4tov4 listenaddre ...

  6. Android工程图片资源命名禁忌

    Android工程中,res\drawable\ 文件夹下所有的图片资源文件命名,不允许: 1. 大写字母 从Eclipse的这个报错可以知道资源文件的命名规则. Invalid file name: ...

  7. emwin之自绘制 BUTTON 图形的一些问题

    @2018-11-8 [小记] [需求] 官方只提供圆角矩形图形,其他图形及颜色需求则要自己实现 [注意] 通过回调函数自实现的图形绘制存在该回调函数一直被调用的现象,而非像窗口回调函数中 BUTTO ...

  8. CSS之FLex布局介绍

    网页布局(layout)是CSS的一个重点应用. img 布局的传统解决方案,基于盒状模型,依赖 display属性 + position属性 + float属性.它对于那些特殊布局非常不方便,比如, ...

  9. [SCOI2015]国旗计划[Wf2014]Surveillance

    [SCOI2015]国旗计划 A国正在开展一项伟大的计划——国旗计划.这项计划的内容是边防战士手举国旗环绕边境线奔袭一圈.这 项计划需要多名边防战士以接力的形式共同完成,为此,国土安全局已经挑选了N名 ...

  10. User Agent 用户代理

    User Agent中文名为用户代理,简称 UA,它是一个特殊字符串头,使得服务器能够识别客户使用的操作系统及版本.CPU 类型.浏览器及版本.浏览器渲染引擎.浏览器语言.浏览器插件等. User A ...