常用框架(二) : spring+springMvc+mybatis+maven+redis

在上一篇常用框架(一)中已经搭建好了基本框架,这里主要是集成 Redis 缓存框架到项目中,作为补充。

需要查看前篇的请点这里跳转:http://blog.csdn.net/mynoteblog/article/details/54922775

先来看下项目结构:


一,在pom.xml 中追加redis依赖包,由于改动比较多,这里还是直接贴上全部内容,以免遗漏:

[html]  view plain  copy
  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.maven.web</groupId>  
  5.     <artifactId>com.maven.web</artifactId>  
  6.     <packaging>war</packaging>  
  7.     <version>0.0.1-SNAPSHOT</version>  
  8.     <name>com.maven.web Maven Webapp</name>  
  9.   
  10.     <properties>  
  11.         <spring.version>4.3.0.RELEASE</spring.version>  
  12.         <jackson.version>2.6.5</jackson.version>  
  13.         <fastjson.version>1.2.23</fastjson.version>  
  14.         <mybatis.version>3.3.0</mybatis.version>  
  15.         <mybatis-spring.version>1.2.3</mybatis-spring.version>  
  16.         <mysql.connector.version>5.1.29</mysql.connector.version>  
  17.         <jedis.version>2.7.3</jedis.version>  
  18.         <spring.data.redis.version>1.7.1.RELEASE</spring.data.redis.version>  
  19.     </properties>  
  20.   
  21.     <repositories>  
  22.         <repository>  
  23.             <id>spring-milestones</id>  
  24.             <name>Spring Milestones</name>  
  25.             <url>https://repo.spring.io/libs-milestone</url>  
  26.             <snapshots>  
  27.                 <enabled>false</enabled>  
  28.             </snapshots>  
  29.         </repository>  
  30.     </repositories>  
  31.   
  32.     <dependencies>  
  33.         <dependency>  
  34.             <groupId>junit</groupId>  
  35.             <artifactId>junit</artifactId>  
  36.             <version>3.8.1</version>  
  37.             <scope>test</scope>  
  38.         </dependency>  
  39.   
  40.         <!-- @Resource注解包 -->  
  41.         <dependency>  
  42.             <groupId>javax.annotation</groupId>  
  43.             <artifactId>javax.annotation-api</artifactId>  
  44.             <version>1.2</version>  
  45.         </dependency>  
  46.   
  47.         <!-- Spring -->  
  48.         <dependency>  
  49.             <groupId>org.springframework</groupId>  
  50.             <artifactId>spring-core</artifactId>  
  51.             <version>${spring.version}</version>  
  52.         </dependency>  
  53.         <dependency>  
  54.             <groupId>org.springframework</groupId>  
  55.             <artifactId>spring-expression</artifactId>  
  56.             <version>${spring.version}</version>  
  57.         </dependency>  
  58.         <dependency>  
  59.             <groupId>org.springframework</groupId>  
  60.             <artifactId>spring-beans</artifactId>  
  61.             <version>${spring.version}</version>  
  62.         </dependency>  
  63.         <dependency>  
  64.             <groupId>org.springframework</groupId>  
  65.             <artifactId>spring-aop</artifactId>  
  66.             <version>${spring.version}</version>  
  67.         </dependency>  
  68.         <dependency>  
  69.             <groupId>org.springframework</groupId>  
  70.             <artifactId>spring-context</artifactId>  
  71.             <version>${spring.version}</version>  
  72.         </dependency>  
  73.         <dependency>  
  74.             <groupId>org.springframework</groupId>  
  75.             <artifactId>spring-context-support</artifactId>  
  76.             <version>${spring.version}</version>  
  77.         </dependency>  
  78.         <dependency>  
  79.             <groupId>org.springframework</groupId>  
  80.             <artifactId>spring-orm</artifactId>  
  81.             <version>${spring.version}</version>  
  82.         </dependency>  
  83.         <dependency>  
  84.             <groupId>org.springframework</groupId>  
  85.             <artifactId>spring-oxm</artifactId>  
  86.             <version>${spring.version}</version>  
  87.         </dependency>  
  88.         <dependency>  
  89.             <groupId>org.springframework</groupId>  
  90.             <artifactId>spring-tx</artifactId>  
  91.             <version>${spring.version}</version>  
  92.         </dependency>  
  93.         <dependency>  
  94.             <groupId>org.springframework</groupId>  
  95.             <artifactId>spring-web</artifactId>  
  96.             <version>${spring.version}</version>  
  97.         </dependency>  
  98.         <dependency>  
  99.             <groupId>org.springframework</groupId>  
  100.             <artifactId>spring-webmvc</artifactId>  
  101.             <version>${spring.version}</version>  
  102.         </dependency>  
  103.   
  104.         <!-- 数据库连接池 -->  
  105.         <dependency>  
  106.             <groupId>commons-dbcp</groupId>  
  107.             <artifactId>commons-dbcp</artifactId>  
  108.             <version>1.4</version>  
  109.         </dependency>  
  110.   
  111.         <!-- mybatis start -->  
  112.         <dependency>  
  113.             <groupId>org.mybatis</groupId>  
  114.             <artifactId>mybatis</artifactId>  
  115.             <version>${mybatis.version}</version>  
  116.         </dependency>  
  117.         <dependency>  
  118.             <groupId>org.mybatis</groupId>  
  119.             <artifactId>mybatis-spring</artifactId>  
  120.             <version>${mybatis-spring.version}</version>  
  121.         </dependency>  
  122.         <dependency>  
  123.             <groupId>org.mybatis</groupId>  
  124.             <artifactId>mybatis-generator-core</artifactId>  
  125.             <version>1.3.2</version>  
  126.         </dependency>  
  127.           
  128.         <!-- mysql -->  
  129.         <dependency>  
  130.             <groupId>mysql</groupId>  
  131.             <artifactId>mysql-connector-java</artifactId>  
  132.             <version>${mysql.connector.version}</version>  
  133.         </dependency>  
  134.   
  135.         <!-- StringUtils -->  
  136.         <dependency>  
  137.             <groupId>org.apache.commons</groupId>  
  138.             <artifactId>commons-lang3</artifactId>  
  139.             <version>3.4</version>  
  140.         </dependency>  
  141.   
  142.         <!-- jackson -->  
  143.         <dependency>  
  144.             <groupId>com.fasterxml.jackson.core</groupId>  
  145.             <artifactId>jackson-core</artifactId>  
  146.             <version>${jackson.version}</version>  
  147.         </dependency>  
  148.         <dependency>  
  149.             <groupId>com.fasterxml.jackson.core</groupId>  
  150.             <artifactId>jackson-databind</artifactId>  
  151.             <version>${jackson.version}</version>  
  152.         </dependency>  
  153.         <dependency>  
  154.             <groupId>com.fasterxml.jackson.core</groupId>  
  155.             <artifactId>jackson-annotations</artifactId>  
  156.             <version>${jackson.version}</version>  
  157.         </dependency>  
  158.   
  159.         <!-- fastjson -->  
  160.         <dependency>  
  161.             <groupId>com.alibaba</groupId>  
  162.             <artifactId>fastjson</artifactId>  
  163.             <version>${fastjson.version}</version>  
  164.         </dependency>  
  165.         <!-- fastjson -->  
  166.   
  167.         <dependency>  
  168.             <groupId>javax.servlet</groupId>  
  169.             <artifactId>javax.servlet-api</artifactId>  
  170.             <version>3.1.0</version>  
  171.             <scope>provided</scope>  
  172.         </dependency>  
  173.           
  174.          <!-- redis start -->  
  175.         <dependency>  
  176.             <groupId>redis.clients</groupId>  
  177.             <artifactId>jedis</artifactId>  
  178.             <version>${jedis.version}</version>  
  179.          </dependency>  
  180.          <dependency>  
  181.             <groupId>org.springframework.data</groupId>  
  182.             <artifactId>spring-data-redis</artifactId>  
  183.             <version>${spring.data.redis.version}</version>  
  184.          </dependency>  
  185.          <!-- redis end -->  
  186.            
  187.     </dependencies>  
  188.   
  189.     <build>  
  190.         <finalName>com.maven.web</finalName>  
  191.     </build>  
  192.   
  193.   
  194. </project>  
二,添加 Spring-redis.xml  配置文件,内容如下:

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xmlns:p="http://www.springframework.org/schema/p"  
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">  
  6.   
  7.     <!-- blockWhenExhausted: 从Pool中获取Jedis对象,Pool资源耗尽后阻塞maxWaitMillis参数指定时间 -->  
  8.     <!-- maxWaitMillis: 从Pool中获取Jedis对象超时时间 -->  
  9.     <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"  
  10.           p:minIdle="2"  
  11.           p:maxIdle="5"  
  12.           p:maxTotal="8"  
  13.           p:maxWaitMillis="2000"  
  14.           p:testOnBorrow="false"  
  15.           p:testOnReturn="false"  
  16.           p:testWhileIdle="true"  
  17.           p:blockWhenExhausted="true" />  
  18.   
  19.     <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">  
  20.         <property name="usePool" value="true" />  
  21.         <property name="hostName" value="192.168.230.130" />  
  22.         <property name="port" value="6379" />  
  23.         <property name="password" value="" />  
  24.         <property name="timeout" value="2000" />  
  25.         <constructor-arg name="poolConfig" ref="jedisPoolConfig" />  
  26.     </bean>  
  27.       
  28.     <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
  29.          <property name="connectionFactory" ref="jedisConnectionFactory" />  
  30.     </bean>  
  31. </beans>  

***********************************

这里需要说明一下:

hostName:填写安装有redis的服务器地址,我这里是安装到本地虚拟机的,如何安装请参看博客:http://www.cnblogs.com/yun965861480/p/6273451.html

port:默认端口是6379

password:自己设置,我这里为空

下面是我启动虚拟机中redis服务的截图,在启动我们项目之前,需要先启动redis:


三,spring-config.xml 原来的配置中引入redis 的配置文件,如下:

[html]  view plain  copy
  1. <import resource="classpath:Spring-redis.xml" />  

四,redis的使用,我这里直接用的工具类,代码分享如下:

(1) RedisService

[java]  view plain  copy
  1. package com.maven.web.redis;  
  2.   
  3. import java.util.Collection;  
  4. import java.util.concurrent.TimeUnit;  
  5. import java.util.function.Supplier;  
  6.   
  7. /** 
  8.  * redis缓存接口。 
  9.  * 
  10.  * 缓存时间单位默认分钟, 
  11.  * 默认timeout值为5, 
  12.  * 没有timeout和timeunit的方法默认不设置有效时间,永久有效。 
  13.  */  
  14. public interface RedisService {  
  15.   
  16.     int EXPIRE_TIME_1 = 1;  
  17.   
  18.     int EXPIRE_TIME_2 = 2;  
  19.   
  20.     int EXPIRE_TIME_5 = 5;  
  21.   
  22.     int EXPIRE_TIME_7 = 7;  
  23.   
  24.     int EXPIRE_TIME_15 = 15;  
  25.       
  26.     int EXPIRE_TIME_30 = 30;  
  27.   
  28.   
  29.     <T> void put(String key, T obj);  
  30.     <T> void put(String key, T obj, int timeout);  
  31.     <T> void put(String key, T obj, int timeout, TimeUnit unit);  
  32.   
  33.     <T> T get(String key, Class<T> cls);  
  34.   
  35.     <E, T extends Collection<E>> T get(String key, Class<E> cls, Class<T> collectionClass);  
  36.   
  37.     <T> T putIfAbsent(String key, Class<T> cls, Supplier<T> supplier);  
  38.     <T> T putIfAbsent(String key, Class<T> cls, Supplier<T> supplier, int timeout);  
  39.     <T> T putIfAbsent(String key, Class<T> cls, Supplier<T> supplier, int timeout, TimeUnit unit);  
  40.     <T> T putIfAbsent(String key, Class<T> cls, Supplier<T> supplier, int timeout, TimeUnit unit, boolean refresh);  
  41.   
  42.     <E, T extends Collection<E>> T putIfAbsent(String key, Class<E> cls, Class<T> collectionCls, Supplier<T> supplier);  
  43.     <E, T extends Collection<E>> T putIfAbsent(String key, Class<E> cls, Class<T> collectionCls, Supplier<T> supplier, int timeout);  
  44.     <E, T extends Collection<E>> T putIfAbsent(String key, Class<E> cls, Class<T> collectionCls, Supplier<T> supplier, int timeout, TimeUnit unit);  
  45.     <E, T extends Collection<E>> T putIfAbsent(String key, Class<E> cls, Class<T> collectionCls, Supplier<T> supplier, int timeout, TimeUnit unit, boolean refresh);  
  46.   
  47.     boolean exists(String key);  
  48.   
  49.     void delete(String key);  
  50.   
  51.     boolean expire(String key, long timeout, TimeUnit timeUnit);  
  52.     boolean expire(String key, long timeout);  
  53.       
  54.     void put(String key, String value);  
  55.     void put(String key, String value, int timeout);  
  56.     void put(String key, String value, int timeout, TimeUnit unit);  
  57.   
  58.     String get(String key);  
  59. }  

(2) RedisServiceImpl

[java]  view plain  copy
  1. package com.maven.web.redis;  
  2.   
  3. import java.util.Collection;  
  4. import java.util.concurrent.TimeUnit;  
  5. import java.util.function.Supplier;  
  6. import org.springframework.beans.factory.annotation.Autowired;  
  7. import org.springframework.data.redis.core.StringRedisTemplate;  
  8. import org.springframework.stereotype.Component;  
  9.   
  10. import com.maven.web.util.JsonUtils;  
  11.   
  12. @Component("redisService")  
  13. public class RedisServiceImpl implements RedisService {  
  14.   
  15.     private StringRedisTemplate redisTemplate;  
  16.   
  17.     @Autowired  
  18.     public void setRedisTemplate(StringRedisTemplate redisTemplate) {  
  19.         this.redisTemplate = redisTemplate;  
  20.     }  
  21.   
  22.     public <T> void put(String key, T obj) {  
  23.         redisTemplate.opsForValue().set(key, JsonUtils.toJson(obj));  
  24.     }  
  25.   
  26.     public <T> void put(String key, T obj, int timeout) {  
  27.         put(key, obj, timeout, TimeUnit.MINUTES);  
  28.     }  
  29.   
  30.     public <T> void put(String key, T obj, int timeout, TimeUnit unit) {  
  31.         redisTemplate.opsForValue().set(key, JsonUtils.toJson(obj), timeout, unit);  
  32.     }  
  33.       
  34.     public <T> T get(String key, Class<T> cls) {  
  35.         return JsonUtils.fromJson(redisTemplate.opsForValue().get(key), cls);  
  36.     }  
  37.       
  38.     public <E, T extends Collection<E>> T get(String key, Class<E> cls, Class<T> collectionClass) {  
  39.         return JsonUtils.fromJson(redisTemplate.opsForValue().get(key), cls, collectionClass);  
  40.     }  
  41.   
  42.     public <T> T putIfAbsent(String key, Class<T> cls, Supplier<T> supplier) {  
  43.         T t = get(key, cls);  
  44.         if (t == null) {  
  45.             t = supplier.get();  
  46.             if (t != null) {  
  47.                 put(key, t);  
  48.             }  
  49.         }  
  50.         return t;  
  51.     }  
  52.   
  53.     public <T> T putIfAbsent(String key, Class<T> cls, Supplier<T> supplier, int timeout) {  
  54.         T t = get(key, cls);  
  55.         if (t == null) {  
  56.             t = supplier.get();  
  57.             if (t != null) {  
  58.                 put(key, t, timeout);  
  59.             }  
  60.         }  
  61.         return t;  
  62.     }  
  63.   
  64.     public <T> T putIfAbsent(String key, Class<T> cls, Supplier<T> supplier, int timeout, TimeUnit unit) {  
  65.         T t = get(key, cls);  
  66.         if (t == null) {  
  67.             t = supplier.get();  
  68.             if (t != null) {  
  69.                 put(key, t, timeout, unit);  
  70.             }  
  71.         }  
  72.         return t;  
  73.     }  
  74.   
  75.     public <T> T putIfAbsent(String key, Class<T> cls, Supplier<T> supplier, int timeout, TimeUnit unit, boolean refresh) {  
  76.         T t = get(key, cls);  
  77.         if (t == null) {  
  78.             t = supplier.get();  
  79.             if (t != null) {  
  80.                 put(key, t, timeout, unit);  
  81.             }  
  82.         } else {  
  83.             if (refresh) {  
  84.                 expire(key, timeout, unit);  
  85.             }  
  86.         }  
  87.         return t;  
  88.     }  
  89.   
  90.     public <E, T extends Collection<E>> T putIfAbsent(String key, Class<E> cls, Class<T> collectionCls, Supplier<T> supplier) {  
  91.         T t = get(key, cls, collectionCls);  
  92.         if (t == null || t.isEmpty()) {  
  93.             t = supplier.get();  
  94.             if (t != null && t.size() > 0) {  
  95.                 put(key, t);  
  96.             }  
  97.         }  
  98.         return t;  
  99.     }  
  100.   
  101.     public <E, T extends Collection<E>> T putIfAbsent(String key, Class<E> cls, Class<T> collectionCls, Supplier<T> supplier, int timeout) {  
  102.         return putIfAbsent(key, cls, collectionCls, supplier, timeout, TimeUnit.SECONDS);  
  103.     }  
  104.   
  105.     public <E, T extends Collection<E>> T putIfAbsent(String key, Class<E> cls, Class<T> collectionCls, Supplier<T> supplier, int timeout, TimeUnit unit) {  
  106.         return putIfAbsent(key, cls, collectionCls, supplier, timeout, unit, false);  
  107.     }  
  108.   
  109.     public <E, T extends Collection<E>> T putIfAbsent(String key, Class<E> cls, Class<T> collectionCls, Supplier<T> supplier, int timeout, TimeUnit unit, boolean refresh) {  
  110.         T t = get(key, cls, collectionCls);  
  111.         if (t == null || t.isEmpty()) {  
  112.             t = supplier.get();  
  113.             if (t != null && t.size() > 0) {  
  114.                 put(key, t, timeout, unit);  
  115.             }  
  116.         } else {  
  117.             if (refresh) {  
  118.                 expire(key, timeout, unit);  
  119.             }  
  120.         }  
  121.         return t;  
  122.     }  
  123.   
  124.   
  125.     public boolean exists(String key) {  
  126.         return redisTemplate.hasKey(key);  
  127.     }  
  128.   
  129.     public void delete(String key) {  
  130.         redisTemplate.delete(key);  
  131.     }  
  132.   
  133.     public boolean expire(String key, long timeout, TimeUnit timeUnit) {  
  134.         return redisTemplate.expire(key, timeout, timeUnit);  
  135.     }  
  136.       
  137.     public boolean expire(String key, long timeout) {  
  138.         return expire(key, timeout, TimeUnit.MINUTES);  
  139.     }  
  140.       
  141.     public void put(String key, String value) {  
  142.         redisTemplate.opsForValue().set(key, value);  
  143.     }  
  144.   
  145.     public void put(String key, String value, int timeout) {  
  146.         put(key, value, timeout, TimeUnit.MINUTES);  
  147.     }  
  148.   
  149.     public void put(String key, String value, int timeout, TimeUnit unit) {  
  150.         redisTemplate.opsForValue().set(key, value, timeout, unit);  
  151.     }  
  152.   
  153.       
  154.     public String get(String key) {  
  155.         return redisTemplate.opsForValue().get(key);  
  156.     }  
  157.       
  158. }  
(3) JsonUtils

[java]  view plain  copy
  1. package com.maven.web.util;  
  2.   
  3. import java.io.IOException;  
  4. import java.text.SimpleDateFormat;  
  5. import java.util.Collection;  
  6.   
  7. import org.apache.commons.lang3.StringUtils;  
  8.   
  9. import com.fasterxml.jackson.core.JsonProcessingException;  
  10. import com.fasterxml.jackson.databind.DeserializationFeature;  
  11. import com.fasterxml.jackson.databind.JavaType;  
  12. import com.fasterxml.jackson.databind.ObjectMapper;  
  13.   
  14. public final class JsonUtils {  
  15.   
  16.     //public static final Logger LOGGER = LoggerFactory.getLogger(JsonUtils.class);  
  17.   
  18.     private JsonUtils() {}  
  19.   
  20.     private static ObjectMapper objectMapper;  
  21.   
  22.     static {  
  23.         objectMapper = new JsonObjectMapper();  
  24.         objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);  
  25.         objectMapper.setDateFormat(new SimpleDateFormat("yyyyMMddHHmmss"));  
  26.     }  
  27.   
  28.     public static <T> String toJson(T obj) {  
  29.         try {  
  30.             return objectMapper.writeValueAsString(obj);  
  31.         } catch (JsonProcessingException e) {  
  32.             e.printStackTrace();  
  33.             //LOGGER.error("class: {} serialize to JSON error: {}", ToStringBuilder.reflectionToString(obj), e);  
  34.         }  
  35.         return null;  
  36.     }  
  37.   
  38.     public static <T> T fromJson(String json, Class<T> cls) {  
  39.         try {  
  40.             if (StringUtils.isBlank(json)) {  
  41.                 return null;  
  42.             }  
  43.             return objectMapper.readValue(json, cls);  
  44.         } catch (IOException e) {  
  45.             e.printStackTrace();  
  46.             //LOGGER.error("deserialize failed! JSON string: {}, class: {}, reason: {}", json, cls, e);  
  47.         }  
  48.         return null;  
  49.     }  
  50.   
  51.     public static <E, T extends Collection<E>> T fromJson(String json, Class<E> cls, Class<T> collectionCls) {  
  52.         if (StringUtils.isBlank(json)) {  
  53.             return null;  
  54.         }  
  55.         JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionCls, cls);  
  56.         try {  
  57.             return objectMapper.readValue(json, javaType);  
  58.         } catch (IOException e) {  
  59.             e.printStackTrace();  
  60.             /*LOGGER.error("deserialize failed! JSON string: {}, Object class:{}, Collection class: {}, reason: {}", 
  61.                     json, cls, collectionCls, e);*/  
  62.         }  
  63.         return null;  
  64.     }  
  65. }  
(4) JsonObjectMapper

[java]  view plain  copy
  1. package com.maven.web.util;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import com.fasterxml.jackson.core.JsonGenerator;  
  6. import com.fasterxml.jackson.core.JsonParser;  
  7. import com.fasterxml.jackson.core.JsonProcessingException;  
  8. import com.fasterxml.jackson.databind.JsonSerializer;  
  9. import com.fasterxml.jackson.databind.ObjectMapper;  
  10. import com.fasterxml.jackson.databind.SerializerProvider;  
  11.   
  12. public class JsonObjectMapper extends ObjectMapper {  
  13.       
  14.     private static final long serialVersionUID = 4769299031472855116L;  
  15.   
  16.     public JsonObjectMapper() {  
  17.         // 允许单引号  
  18.         this.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);  
  19.         // 字段和值都加引号  
  20.         this.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);  
  21.         // 数字也加引号  
  22.         /*this.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true); 
  23.         this.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, true);*/  
  24.         // 空值处理为空串  
  25.         this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {  
  26.   
  27.             @Override  
  28.             public void serialize(  
  29.                     Object value,  
  30.                     JsonGenerator jg,  
  31.                     SerializerProvider sp) throws IOException, JsonProcessingException {  
  32.                 jg.writeString("");  
  33.             }  
  34.         });  
  35.     }  
  36. }  

五,准备工作做好了,接下来是测试

(1) 新增RedisController,代码如下:

[java]  view plain  copy
  1. package com.maven.web.controller;  
  2.   
  3. import javax.annotation.Resource;  
  4.   
  5. import org.springframework.stereotype.Controller;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.bind.annotation.RequestMethod;  
  8. import org.springframework.web.bind.annotation.RequestParam;  
  9. import org.springframework.web.bind.annotation.ResponseBody;  
  10.   
  11. import com.maven.web.entity.UserInfo;  
  12. import com.maven.web.service.impl.UserService;  
  13.   
  14. @Controller  
  15. @RequestMapping("/redis")  
  16. public class RedisController {  
  17.       
  18.     @Resource  
  19.     private UserService userService;  
  20.       
  21.     @ResponseBody  
  22.     @RequestMapping(value="/userInfo",method=RequestMethod.GET)  
  23.     public String getUserInfo(@RequestParam Long uid){  
  24.         UserInfo userInfo = userService.getUserInfo(uid);  
  25.         if(userInfo!=null){  
  26.             return "您要获取的用户名称是:"+userInfo.getUserName();  
  27.         }  
  28.         return "获取用户信息失败";  
  29.     }  
  30.   
  31. }  
(2) UserService 中添加方法,从缓存中获取用户信息,代码片段如下:

[java]  view plain  copy
  1. /** 从缓存中获取 */  
  2.     UserInfo getUserInfo(Long uid);  
(3) UserServiceImpl 实现,代码片段如下:

[java]  view plain  copy
  1. public UserInfo getUserInfo(Long uid) {  
  2.         String json = redisService.get(USER_INFO+uid);  
  3.         if(json==null){  
  4.             UserInfo userInfo = select(uid);  
  5.             if(userInfo!=null){  
  6.                 redisService.put(USER_INFO+uid, userInfo, 1, TimeUnit.HOURS);  
  7.             }  
  8.             return userInfo;  
  9.         }  
  10.   
  11.         return JsonUtils.fromJson(json, UserInfo.class);  
  12.     }  
六,启动tomcat,测试,我这里用的是google应用,postman

开启debug模式进入后台可以看到,第一次是从数据库查询数据,第二次就是从缓存取数据了:


再看返回结果:



**********************************************************************************************

测试成功,到此集成redis框架就完成了,需要参考项目源码的请点这里:http://pan.baidu.com/s/1kVPrPmZ










猜你喜欢

转载自blog.csdn.net/qq_27676247/article/details/74280103