springmvc+mybatis+redis(转)
最近在学习redis的使用方法,它的本地使用方法比较简单,只需要先启动Redis服务器,然后运行测试代码即可。但是现在我想要在网站上访问数据库的时候采用Redis缓存,问题就出来了。要么是缓存直接失效,每次都是直接访问数据库,要么就是出错。在网上看了很久发现一个靠谱的方法,和大家分享一下。
redis相关类是采用注解的形式,因此首先扫描注解类
- <!-- class annotation related... start -->
- <context:component-scan base-package="com.defonds.bdp.*.service" />
- <context:component-scan base-package="com.defonds.bdp.cache.redis" />
- <!-- class annotation related... end -->
- <context:annotation-config />
缓存工具类如下:
- /**
- * File Name:RedisCacheConfig.java
- *
- * Copyright Defonds Corporation 2015
- * All Rights Reserved
- *
- */
- package com.defonds.bdp.cache.redis;
- import org.springframework.cache.CacheManager;
- import org.springframework.cache.annotation.CachingConfigurerSupport;
- import org.springframework.cache.annotation.EnableCaching;
- import org.springframework.cache.interceptor.KeyGenerator;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.data.redis.cache.RedisCacheManager;
- import org.springframework.data.redis.connection.RedisConnectionFactory;
- import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
- import org.springframework.data.redis.core.RedisTemplate;
- import java.lang.reflect.Method;
- /**
- *
- * Project Name:bdp
- * Type Name:RedisCacheConfig
- * Type Description:
- * Author:Defonds
- * Create Date:2015-09-21
- *
- * @version
- *
- */
- @Configuration
- @EnableCaching
- public class RedisCacheConfig extends CachingConfigurerSupport {
- @Bean
- public JedisConnectionFactory redisConnectionFactory() {
- JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
- // Defaults
- redisConnectionFactory.setHostName("127.0.0.1");
- redisConnectionFactory.setPort(6379);
- return redisConnectionFactory;
- }
- @Bean
- public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {
- RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
- redisTemplate.setConnectionFactory(cf);
- return redisTemplate;
- }
- @Bean
- public CacheManager cacheManager(RedisTemplate redisTemplate) {
- RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
- // Number of seconds before expiration. Defaults to unlimited (0)
- cacheManager.setDefaultExpiration(3000); // Sets the default expire time (in seconds)
- return cacheManager;
- }
- @Bean
- public KeyGenerator customKeyGenerator() {
- return new KeyGenerator() {
- public Object generate(Object o, Method method, Object... objects) {
- StringBuilder sb = new StringBuilder();
- sb.append(o.getClass().getName());
- sb.append(method.getName());
- for (Object obj : objects) {
- sb.append(obj.toString());
- }
- return sb.toString();
- }
- };
- }
- }
缓存的使用是在service层,在方法上使用注解,调用缓存
- /**
- * File Name:CityService.java
- *
- * Copyright Defonds Corporation 2015
- * All Rights Reserved
- *
- */
- package com.defonds.bdp.city.service;
- import java.util.List;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.cache.annotation.CacheEvict;
- import org.springframework.cache.annotation.Cacheable;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Propagation;
- import org.springframework.transaction.annotation.Transactional;
- import com.defonds.bdp.city.bean.City;
- import com.defonds.bdp.city.mapper.CityMapper;
- /**
- *
- * Project Name:bdp
- * Type Name:CityService
- * Type Description:
- * Author:Defonds
- * Create Date:2015-08-31
- * @version
- *
- */
- @Service
- @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
- public class CityService {
- private final Log logger = LogFactory.getLog(this.getClass());
- @Autowired
- private CityMapper cityMapper;
- // C
- @CacheEvict(value = { "provinceCities"}, allEntries = true)
- public void insertCity(String city_code, String city_jb,
- String province_code, String city_name,
- String city, String province) {
- City cityBean = new City();
- cityBean.setCityCode(city_code);
- cityBean.setCityJb(city_jb);
- cityBean.setProvinceCode(province_code);
- cityBean.setCityName(city_name);
- cityBean.setCity(city);
- cityBean.setProvince(province);
- this.cityMapper.insertCity(cityBean);
- }
- // R
- @Cacheable("provinceCities")
- public List<City> provinceCities(String province) {
- logger.debug("province=" + province);
- return this.cityMapper.provinceCities(province);
- }
- // R
- @Cacheable("searchCity")
- public City searchCity(String city_code){
- logger.debug("city_code=" + city_code);
- return this.cityMapper.searchCity(city_code);
- }
- // U
- @CacheEvict(value = { "provinceCities", "searchCity" }, allEntries = true)
- public int renameCity(String city_code, String city_name) {
- City city = new City();
- city.setCityCode(city_code);
- city.setCityName(city_name);
- this.cityMapper.renameCity(city);
- return 1;
- }
- // D
- @CacheEvict(value = { "provinceCities", "searchCity" }, allEntries = true)
- public int deleteCity(String city_code) {
- this.cityMapper.deleteCity(city_code);
- return 1;
- }
- }
maven项目,增加redis的jar包
- <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>
- <groupId>com</groupId>
- <artifactId>redisdemo01</artifactId>
- <packaging>war</packaging>
- <version>0.0.1-SNAPSHOT</version>
- <name>redisdemo01 Maven Webapp</name>
- <url>http://maven.apache.org</url>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <spring.version>4.1.4.RELEASE</spring.version>
- <jackson.version>2.5.0</jackson.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.12</version>
- <scope>test</scope>
- </dependency>
- <!-- spring -->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-core</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-beans</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-tx</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-web</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jdbc</artifactId>
- <version>${spring.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-test</artifactId>
- <version>${spring.version}</version>
- <scope>test</scope>
- </dependency>
- <!-- mybatis 包 -->
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis</artifactId>
- <version>3.2.8</version>
- </dependency>
- <!--mybatis spring 插件 -->
- <dependency>
- <groupId>org.mybatis</groupId>
- <artifactId>mybatis-spring</artifactId>
- <version>1.2.2</version>
- </dependency>
- <!-- mysql连接 -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.34</version>
- </dependency>
- <!-- 数据源 -->
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.0.12</version>
- </dependency>
- <dependency>
- <groupId>c3p0</groupId>
- <artifactId>c3p0</artifactId>
- <version>0.9.1.2</version>
- </dependency>
- <dependency>
- <groupId>org.aspectj</groupId>
- <artifactId>aspectjweaver</artifactId>
- <version>1.8.4</version>
- </dependency>
- <!-- log4j -->
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>1.2.17</version>
- </dependency>
- <!-- servlet -->
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>3.0-alpha-1</version>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>jstl</artifactId>
- <version>1.2</version>
- </dependency>
- <!-- json -->
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-mapper-asl</artifactId>
- <version>1.9.13</version>
- </dependency>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>fastjson</artifactId>
- <version>1.2.3</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-annotations</artifactId>
- <version>${jackson.version}</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- <version>${jackson.version}</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>${jackson.version}</version>
- </dependency>
- <!-- 文件上传 -->
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.4</version>
- </dependency>
- <dependency>
- <groupId>commons-fileupload</groupId>
- <artifactId>commons-fileupload</artifactId>
- <version>1.2.2</version>
- </dependency>
- <!-- 队列 -->
- <dependency>
- <groupId>com.rabbitmq</groupId>
- <artifactId>amqp-client</artifactId>
- <version>3.4.1</version>
- </dependency>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- <version>1.7.7</version>
- </dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <version>3.3.2</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.amqp</groupId>
- <artifactId>spring-rabbit</artifactId>
- <version>1.4.0.RELEASE</version>
- </dependency>
- <!-- 缓存 -->
- <dependency>
- <groupId>redis.clients</groupId>
- <artifactId>jedis</artifactId>
- <version>2.6.0</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.data</groupId>
- <artifactId>spring-data-redis</artifactId>
- <version>1.6.0.RELEASE</version>
- </dependency>
- </dependencies>
- <build>
- <finalName>redisdemo01</finalName>
- </build>
- </project>
web.xml不变
- <!DOCTYPE web-app PUBLIC
- "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
- "http://java.sun.com/dtd/web-app_2_3.dtd" >
- <web-app>
- <display-name>Archetype Created Web Application</display-name>
- <filter>
- <filter-name>encodingFilter</filter-name>
- <filter-class>
- org.springframework.web.filter.CharacterEncodingFilter
- </filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- <init-param>
- <param-name>forceEncoding</param-name>
- <param-value>true</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>encodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <!-- 除了加过滤器,由于tomcat默认编码ISO-8859-1,还需要修改 %tomcat%/conf/server.xml Connector 标签加属性 URIEncoding="UTF-8" -->
- <!-- character encoding related.....end -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/classes/*-applicationContext.xml</param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <servlet>
- <servlet-name>bdpmvc</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/classes/*-servlet.xml</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>bdpmvc</servlet-name>
- <url-pattern>/</url-pattern>
- <!-- <url-pattern>*.json</url-pattern>
- <url-pattern>*.html</url-pattern> -->
- </servlet-mapping>
- </web-app>
http://blog.csdn.net/u010627840/article/details/50593659