springmvc+mybatis+redis(转)

最近在学习redis的使用方法,它的本地使用方法比较简单,只需要先启动Redis服务器,然后运行测试代码即可。但是现在我想要在网站上访问数据库的时候采用Redis缓存,问题就出来了。要么是缓存直接失效,每次都是直接访问数据库,要么就是出错。在网上看了很久发现一个靠谱的方法,和大家分享一下。

redis相关类是采用注解的形式,因此首先扫描注解类

 

[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <!-- class annotation related... start -->  
  2.     <context:component-scan base-package="com.defonds.bdp.*.service" />  
  3.     <context:component-scan base-package="com.defonds.bdp.cache.redis" />  
  4.     <!-- class annotation related... end -->  
  5.     <context:annotation-config />  


缓存工具类如下:

 

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * File Name:RedisCacheConfig.java 
  3.  * 
  4.  * Copyright Defonds Corporation 2015  
  5.  * All Rights Reserved 
  6.  * 
  7.  */  
  8. package com.defonds.bdp.cache.redis;  
  9.   
  10. import org.springframework.cache.CacheManager;  
  11. import org.springframework.cache.annotation.CachingConfigurerSupport;  
  12. import org.springframework.cache.annotation.EnableCaching;  
  13. import org.springframework.cache.interceptor.KeyGenerator;  
  14. import org.springframework.context.annotation.Bean;  
  15. import org.springframework.context.annotation.Configuration;  
  16. import org.springframework.data.redis.cache.RedisCacheManager;  
  17. import org.springframework.data.redis.connection.RedisConnectionFactory;  
  18. import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;  
  19. import org.springframework.data.redis.core.RedisTemplate;  
  20.   
  21. import java.lang.reflect.Method;  
  22.   
  23. /** 
  24.  *  
  25.  * Project Name:bdp  
  26.  * Type Name:RedisCacheConfig  
  27.  * Type Description: 
  28.  *  Author:Defonds 
  29.  * Create Date:2015-09-21 
  30.  *  
  31.  * @version 
  32.  *  
  33.  */  
  34. @Configuration  
  35. @EnableCaching  
  36. public class RedisCacheConfig extends CachingConfigurerSupport {  
  37.   
  38.     @Bean  
  39.     public JedisConnectionFactory redisConnectionFactory() {  
  40.         JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();  
  41.   
  42.         // Defaults  
  43.         redisConnectionFactory.setHostName("127.0.0.1");  
  44.         redisConnectionFactory.setPort(6379);  
  45.         return redisConnectionFactory;  
  46.     }  
  47.   
  48.     @Bean  
  49.     public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {  
  50.         RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();  
  51.         redisTemplate.setConnectionFactory(cf);  
  52.         return redisTemplate;  
  53.     }  
  54.   
  55.     @Bean  
  56.     public CacheManager cacheManager(RedisTemplate redisTemplate) {  
  57.         RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);  
  58.   
  59.         // Number of seconds before expiration. Defaults to unlimited (0)  
  60.         cacheManager.setDefaultExpiration(3000); // Sets the default expire time (in seconds)  
  61.         return cacheManager;  
  62.     }  
  63.       
  64.     @Bean  
  65.     public KeyGenerator customKeyGenerator() {  
  66.         return new KeyGenerator() {  
  67.             public Object generate(Object o, Method method, Object... objects) {  
  68.                 StringBuilder sb = new StringBuilder();  
  69.                 sb.append(o.getClass().getName());  
  70.                 sb.append(method.getName());  
  71.                 for (Object obj : objects) {  
  72.                     sb.append(obj.toString());  
  73.                 }  
  74.                 return sb.toString();  
  75.             }  
  76.         };  
  77.     }  
  78. }  


缓存的使用是在service层,在方法上使用注解,调用缓存

 

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * File Name:CityService.java 
  3.  * 
  4.  * Copyright Defonds Corporation 2015  
  5.  * All Rights Reserved 
  6.  * 
  7.  */  
  8. package com.defonds.bdp.city.service;  
  9.   
  10. import java.util.List;  
  11.   
  12. import org.apache.commons.logging.Log;  
  13. import org.apache.commons.logging.LogFactory;  
  14. import org.springframework.beans.factory.annotation.Autowired;  
  15. import org.springframework.cache.annotation.CacheEvict;  
  16. import org.springframework.cache.annotation.Cacheable;  
  17. import org.springframework.stereotype.Service;  
  18. import org.springframework.transaction.annotation.Propagation;  
  19. import org.springframework.transaction.annotation.Transactional;  
  20.   
  21. import com.defonds.bdp.city.bean.City;  
  22. import com.defonds.bdp.city.mapper.CityMapper;  
  23.   
  24. /** 
  25.  *  
  26.  * Project Name:bdp 
  27.  * Type Name:CityService 
  28.  * Type Description: 
  29.  * Author:Defonds 
  30.  * Create Date:2015-08-31 
  31.  * @version  
  32.  *  
  33.  */  
  34. @Service  
  35. @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)  
  36. public class CityService {   
  37.     private final Log logger = LogFactory.getLog(this.getClass());  
  38.     @Autowired  
  39.     private CityMapper cityMapper;  
  40.       
  41.     // C  
  42.     @CacheEvict(value = { "provinceCities"}, allEntries = true)  
  43.     public void insertCity(String city_code, String city_jb,   
  44.             String province_code, String city_name,  
  45.             String city, String province) {  
  46.         City cityBean = new City();  
  47.         cityBean.setCityCode(city_code);  
  48.         cityBean.setCityJb(city_jb);  
  49.         cityBean.setProvinceCode(province_code);  
  50.         cityBean.setCityName(city_name);  
  51.         cityBean.setCity(city);  
  52.         cityBean.setProvince(province);  
  53.         this.cityMapper.insertCity(cityBean);  
  54.     }  
  55.       
  56.     // R  
  57.     @Cacheable("provinceCities")  
  58.     public List<City> provinceCities(String province) {  
  59.         logger.debug("province=" + province);  
  60.         return this.cityMapper.provinceCities(province);  
  61.     }  
  62.       
  63.     // R  
  64.     @Cacheable("searchCity")  
  65.     public City searchCity(String city_code){  
  66.         logger.debug("city_code=" + city_code);  
  67.         return this.cityMapper.searchCity(city_code);     
  68.     }  
  69.       
  70.     // U  
  71.     @CacheEvict(value = { "provinceCities", "searchCity" }, allEntries = true)  
  72.     public int renameCity(String city_code, String city_name) {  
  73.         City city = new City();  
  74.         city.setCityCode(city_code);  
  75.         city.setCityName(city_name);  
  76.         this.cityMapper.renameCity(city);  
  77.         return 1;  
  78.     }  
  79.       
  80.     // D  
  81.     @CacheEvict(value = { "provinceCities", "searchCity" }, allEntries = true)  
  82.     public int deleteCity(String city_code) {  
  83.         this.cityMapper.deleteCity(city_code);  
  84.         return 1;  
  85.     }  
  86. }  

 

 

maven项目,增加redis的jar包

 

[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  3.   <modelVersion>4.0.0</modelVersion>  
  4.   <groupId>com</groupId>  
  5.   <artifactId>redisdemo01</artifactId>  
  6.   <packaging>war</packaging>  
  7.   <version>0.0.1-SNAPSHOT</version>  
  8.   <name>redisdemo01 Maven Webapp</name>  
  9.   <url>http://maven.apache.org</url>  
  10.    
  11.  <properties>  
  12.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  13.         <spring.version>4.1.4.RELEASE</spring.version>  
  14.         <jackson.version>2.5.0</jackson.version>  
  15.     </properties>  
  16.   
  17.     <dependencies>  
  18.   
  19.         <dependency>  
  20.             <groupId>junit</groupId>  
  21.             <artifactId>junit</artifactId>  
  22.             <version>4.12</version>  
  23.             <scope>test</scope>  
  24.         </dependency>  
  25.   
  26.         <!-- spring -->  
  27.         <dependency>  
  28.             <groupId>org.springframework</groupId>  
  29.             <artifactId>spring-core</artifactId>  
  30.             <version>${spring.version}</version>  
  31.         </dependency>  
  32.   
  33.         <dependency>  
  34.             <groupId>org.springframework</groupId>  
  35.             <artifactId>spring-beans</artifactId>  
  36.             <version>${spring.version}</version>  
  37.         </dependency>  
  38.   
  39.         <dependency>  
  40.             <groupId>org.springframework</groupId>  
  41.             <artifactId>spring-context</artifactId>  
  42.             <version>${spring.version}</version>  
  43.         </dependency>  
  44.   
  45.         <dependency>  
  46.             <groupId>org.springframework</groupId>  
  47.             <artifactId>spring-tx</artifactId>  
  48.             <version>${spring.version}</version>  
  49.         </dependency>  
  50.   
  51.         <dependency>  
  52.             <groupId>org.springframework</groupId>  
  53.             <artifactId>spring-web</artifactId>  
  54.             <version>${spring.version}</version>  
  55.         </dependency>  
  56.   
  57.         <dependency>  
  58.             <groupId>org.springframework</groupId>  
  59.             <artifactId>spring-webmvc</artifactId>  
  60.             <version>${spring.version}</version>  
  61.         </dependency>  
  62.   
  63.         <dependency>  
  64.             <groupId>org.springframework</groupId>  
  65.             <artifactId>spring-jdbc</artifactId>  
  66.             <version>${spring.version}</version>  
  67.         </dependency>  
  68.   
  69.         <dependency>  
  70.             <groupId>org.springframework</groupId>  
  71.             <artifactId>spring-test</artifactId>  
  72.             <version>${spring.version}</version>  
  73.             <scope>test</scope>  
  74.         </dependency>  
  75.   
  76.         <!-- mybatis 包 -->  
  77.         <dependency>  
  78.             <groupId>org.mybatis</groupId>  
  79.             <artifactId>mybatis</artifactId>  
  80.             <version>3.2.8</version>  
  81.         </dependency>  
  82.   
  83.         <!--mybatis spring 插件 -->  
  84.         <dependency>  
  85.             <groupId>org.mybatis</groupId>  
  86.             <artifactId>mybatis-spring</artifactId>  
  87.             <version>1.2.2</version>  
  88.         </dependency>  
  89.   
  90.         <!-- mysql连接 -->  
  91.         <dependency>  
  92.             <groupId>mysql</groupId>  
  93.             <artifactId>mysql-connector-java</artifactId>  
  94.             <version>5.1.34</version>  
  95.         </dependency>  
  96.   
  97.         <!-- 数据源 -->  
  98.         <dependency>  
  99.             <groupId>com.alibaba</groupId>  
  100.             <artifactId>druid</artifactId>  
  101.             <version>1.0.12</version>  
  102.         </dependency>  
  103.           
  104.         <dependency>  
  105.             <groupId>c3p0</groupId>  
  106.             <artifactId>c3p0</artifactId>  
  107.             <version>0.9.1.2</version>  
  108.         </dependency>  
  109.   
  110.         <dependency>  
  111.             <groupId>org.aspectj</groupId>  
  112.             <artifactId>aspectjweaver</artifactId>  
  113.             <version>1.8.4</version>  
  114.         </dependency>  
  115.   
  116.         <!-- log4j -->  
  117.         <dependency>  
  118.             <groupId>log4j</groupId>  
  119.             <artifactId>log4j</artifactId>  
  120.             <version>1.2.17</version>  
  121.         </dependency>  
  122.   
  123.         <!-- servlet -->  
  124.         <dependency>  
  125.             <groupId>javax.servlet</groupId>  
  126.             <artifactId>servlet-api</artifactId>  
  127.             <version>3.0-alpha-1</version>  
  128.         </dependency>  
  129.   
  130.         <dependency>  
  131.             <groupId>javax.servlet</groupId>  
  132.             <artifactId>jstl</artifactId>  
  133.             <version>1.2</version>  
  134.         </dependency>  
  135.   
  136.         <!-- json -->  
  137.         <dependency>  
  138.             <groupId>org.codehaus.jackson</groupId>  
  139.             <artifactId>jackson-mapper-asl</artifactId>  
  140.             <version>1.9.13</version>  
  141.         </dependency>  
  142.   
  143.         <dependency>  
  144.             <groupId>com.alibaba</groupId>  
  145.             <artifactId>fastjson</artifactId>  
  146.             <version>1.2.3</version>  
  147.         </dependency>  
  148.   
  149.         <dependency>  
  150.             <groupId>com.fasterxml.jackson.core</groupId>  
  151.             <artifactId>jackson-annotations</artifactId>  
  152.             <version>${jackson.version}</version>  
  153.         </dependency>  
  154.   
  155.         <dependency>  
  156.             <groupId>com.fasterxml.jackson.core</groupId>  
  157.             <artifactId>jackson-core</artifactId>  
  158.             <version>${jackson.version}</version>  
  159.         </dependency>  
  160.   
  161.         <dependency>  
  162.             <groupId>com.fasterxml.jackson.core</groupId>  
  163.             <artifactId>jackson-databind</artifactId>  
  164.             <version>${jackson.version}</version>  
  165.         </dependency>  
  166.         <!-- 文件上传 -->  
  167.         <dependency>  
  168.             <groupId>commons-io</groupId>  
  169.             <artifactId>commons-io</artifactId>  
  170.             <version>2.4</version>  
  171.         </dependency>  
  172.   
  173.         <dependency>  
  174.             <groupId>commons-fileupload</groupId>  
  175.             <artifactId>commons-fileupload</artifactId>  
  176.             <version>1.2.2</version>  
  177.         </dependency>  
  178.       
  179.         <!-- 队列 -->  
  180.         <dependency>  
  181.             <groupId>com.rabbitmq</groupId>  
  182.             <artifactId>amqp-client</artifactId>  
  183.             <version>3.4.1</version>  
  184.     </dependency>  
  185.     <dependency>  
  186.             <groupId>org.slf4j</groupId>  
  187.             <artifactId>slf4j-log4j12</artifactId>  
  188.             <version>1.7.7</version>  
  189.     </dependency>  
  190.     <dependency>  
  191.             <groupId>org.apache.commons</groupId>  
  192.             <artifactId>commons-lang3</artifactId>  
  193.             <version>3.3.2</version>  
  194.     </dependency>  
  195.           
  196.     <dependency>  
  197.             <groupId>org.springframework.amqp</groupId>  
  198.             <artifactId>spring-rabbit</artifactId>  
  199.             <version>1.4.0.RELEASE</version>  
  200.     </dependency>  
  201.       
  202.     <!-- 缓存 -->  
  203.     <dependency>  
  204.             <groupId>redis.clients</groupId>  
  205.             <artifactId>jedis</artifactId>  
  206.             <version>2.6.0</version>  
  207.     </dependency>  
  208.       
  209.     <dependency>  
  210.             <groupId>org.springframework.data</groupId>  
  211.             <artifactId>spring-data-redis</artifactId>  
  212.             <version>1.6.0.RELEASE</version>  
  213.     </dependency>  
  214.   
  215.     </dependencies>  
  216.   <build>  
  217.     <finalName>redisdemo01</finalName>  
  218.   </build>  
  219. </project>  


web.xml不变

 

 

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
    1. <!DOCTYPE web-app PUBLIC  
    2.  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"  
    3.  "http://java.sun.com/dtd/web-app_2_3.dtd" >  
    4.   
    5. <web-app>  
    6.   <display-name>Archetype Created Web Application</display-name>  
    7.   <filter>  
    8.         <filter-name>encodingFilter</filter-name>  
    9.         <filter-class>  
    10.                 org.springframework.web.filter.CharacterEncodingFilter   
    11.         </filter-class>  
    12.         <init-param>  
    13.                <param-name>encoding</param-name>  
    14.                <param-value>UTF-8</param-value>  
    15.         </init-param>  
    16.         <init-param>  
    17.                <param-name>forceEncoding</param-name>  
    18.                <param-value>true</param-value>  
    19.         </init-param>  
    20.     </filter>  
    21.     <filter-mapping>  
    22.           <filter-name>encodingFilter</filter-name>  
    23.           <url-pattern>/*</url-pattern>  
    24.     </filter-mapping>  
    25.     <!-- 除了加过滤器,由于tomcat默认编码ISO-8859-1,还需要修改 %tomcat%/conf/server.xml Connector 标签加属性 URIEncoding="UTF-8" -->  
    26.     <!-- character encoding related.....end -->  
    27.   
    28.     <context-param>  
    29.         <param-name>contextConfigLocation</param-name>  
    30.         <param-value>/WEB-INF/classes/*-applicationContext.xml</param-value>  
    31.     </context-param>  
    32.     <listener>  
    33.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    34.     </listener>  
    35.   
    36.     <servlet>  
    37.         <servlet-name>bdpmvc</servlet-name>  
    38.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    39.         <init-param>  
    40.             <param-name>contextConfigLocation</param-name>  
    41.             <param-value>/WEB-INF/classes/*-servlet.xml</param-value>  
    42.         </init-param>  
    43.         <load-on-startup>1</load-on-startup>  
    44.     </servlet>  
    45.     <servlet-mapping>  
    46.         <servlet-name>bdpmvc</servlet-name>  
    47.         <url-pattern>/</url-pattern>  
    48.         <!-- <url-pattern>*.json</url-pattern>  
    49.         <url-pattern>*.html</url-pattern> -->  
    50.     </servlet-mapping>  
    51. </web-app>  

http://blog.csdn.net/u010627840/article/details/50593659

 

posted @ 2016-06-25 23:39  沧海一滴  阅读(763)  评论(0编辑  收藏  举报