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包下载) ...
随机推荐
- thinkphp 5内置验证规则-基本版
内置规则 系统内置的验证规则如下: 格式验证类 require 验证某个字段必须,例如: 'name'=>'require' number 或者 integer 验证某个字段的值是否为数字(采用 ...
- Gogs 部署安装(Linux)
环境 centos7:golang+mysqldb+git. 安装配置环境[mysql装了请跳过] yum install mysql-community-server go git -y 配置防火墙 ...
- python学习日记(装饰器的补充)
如何返回被装饰函数的函数名及注释? 问题及实现 先看典型的装饰器: def wrapper(f):#装饰器函数,f是被装饰函数 def inner(*args,**kwargs): '''执行函数之前 ...
- 【NOI2002】
A 银河英雄传说 带权并查集 B 贪吃的九头龙 树形dp f[x][j][0] = min(f[x][j][0], min(f[vv][t][0] + tmp[j - t][0] + ww * (m ...
- Android 开发中 SQLite 数据库的使用
SQLite 介绍 SQLite 一个非常流行的嵌入式数据库,它支持 SQL 语言,并且只利用很少的内存就有很好的性能.此外它还是开源的,任何人都可以使用它.许多开源项目((Mozilla, PHP, ...
- 【BZOJ5212】[ZJOI2018]历史(Link-Cut Tree)
[BZOJ5212][ZJOI2018]历史(Link-Cut Tree) 题面 洛谷 BZOJ 题解 显然实际上就是给定了一棵树和每个点被\(access\)的次数,求解轻重链切换的最大次数. 先考 ...
- Codeforces | CF1029C 【Maximal Intersection】
论Div3出这样巨水的送分题竟然还没多少人AC(虽说当时我也没A...其实我A了D...逃) 这个题其实一点都不麻烦,排序都可以免掉(如果用\(priority \_ queue\)的话) 先考虑不删 ...
- 软硬连接ln
软硬连接Linux链接概念Linux链接分两种,一种被称为硬链接(Hard Link),另一种被称为符号链接(Symbolic Link).默认情况下,ln命令产生硬链接. [硬连接]硬连接指通过索引 ...
- 2018 ICPC 焦作网络赛 E.Jiu Yuan Wants to Eat
题意:四个操作,区间加,区间每个数乘,区间的数变成 2^64-1-x,求区间和. 题解:2^64-1-x=(2^64-1)-x 因为模数为2^64,-x%2^64=-1*x%2^64 由负数取模的性质 ...
- SpaceVim中vimproc的vimproc_linux64.so未找到
vimproc是我使用的SpaceVim中自动安装的插件,在启动时出现了"找不到dll文件"的提示,通过查阅官网( https://github.com/Shougo/vimpro ...