Redis整合Spring结合使用缓存实例

开发 前端 Redis
本文介绍了如何在Spring中配置redis,并通过Spring中AOP的思想,将缓存的方法切入到有需要进入缓存的类或方法前面。

一、Redis介绍

什么是Redis?

redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、 list(链表)、set(集合)、zset(sorted set –有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原 子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的 把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。

它有什么特点?

(1)Redis数据库完全在内存中,使用磁盘仅用于持久性。
(2)相比许多键值数据存储,Redis拥有一套较为丰富的数据类型。
(3)Redis可以将数据复制到任意数量的从服务器。

Redis 优势?

(1)异常快速:Redis的速度非常快,每秒能执行约11万集合,每秒约81000+条记录。
(2)支持丰富的数据类型:Redis支持***多数开发人员已经知道像列表,集合,有序集合,散列数据类型。这使得它非常容易解决各种各样的问题,因为我们知道哪些问题是可以处理通过它的数据类型更好。
(3)操作都是原子性:所有Redis操作是原子的,这保证了如果两个客户端同时访问的Redis服务器将获得更新后的值。
(4)多功能实用工具:Redis是一个多实用的工具,可以在多个用例如缓存,消息,队列使用(Redis原生支持发布/订阅),任何短暂的数据,应用程序,如Web应用程序会话,网页***计数等。

Redis 缺点?

(1)单线程

(2)耗内存

二、使用实例

本文使用maven+eclipse+sping

1、引入jar包

  1.     <!--Redis start --> 
  2. <dependency> 
  3.  <groupId>org.springframework.data</groupId> 
  4.  <artifactId>spring-data-redis</artifactId> 
  5.  <version>1.6.1.RELEASE</version> 
  6. </dependency> 
  7. <dependency> 
  8.  <groupId>redis.clients</groupId> 
  9.  <artifactId>jedis</artifactId> 
  10.  <version>2.7.3</version> 
  11. </dependency> 
  12.    <!--Redis end --> 

2、配置bean

在application.xml加入如下配置

  1. <!-- jedis 配置 --> 
  2.     <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig" > 
  3.           <property name="maxIdle" value="${redis.maxIdle}" /> 
  4.           <property name="maxWaitMillis" value="${redis.maxWait}" /> 
  5.           <property name="testOnBorrow" value="${redis.testOnBorrow}" /> 
  6.     </bean > 
  7.    <!-- redis服务器中心 --> 
  8.     <bean id="connectionFactory"  class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" > 
  9.           <property name="poolConfig" ref="poolConfig" /> 
  10.           <property name="port" value="${redis.port}" /> 
  11.           <property name="hostName" value="${redis.host}" /> 
  12.           <property name="password" value="${redis.password}" /> 
  13.           <property name="timeout" value="${redis.timeout}" ></property> 
  14.     </bean > 
  15.     <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" > 
  16.           <property name="connectionFactory" ref="connectionFactory" /> 
  17.           <property name="keySerializer" > 
  18.               <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> 
  19.           </property> 
  20.           <property name="valueSerializer" > 
  21.               <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> 
  22.           </property> 
  23.     </bean > 
  24.  
  25.      <!-- cache配置 --> 
  26.     <bean id="methodCacheInterceptor" class="com.mucfc.msm.common.MethodCacheInterceptor" > 
  27.           <property name="redisUtil" ref="redisUtil" /> 
  28.     </bean > 
  29.     <bean id="redisUtil" class="com.mucfc.msm.common.RedisUtil" > 
  30.           <property name="redisTemplate" ref="redisTemplate" /> 
  31.     </bean > 

其中配置文件redis一些配置数据redis.properties如下:

  1. #redis中心 
  2. redis.host=10.75.202.11 
  3. redis.port=6379 
  4. redis.password=123456 
  5. redis.maxIdle=100 
  6. redis.maxActive=300 
  7. redis.maxWait=1000 
  8. redis.testOnBorrow=true 
  9. redis.timeout=100000 
  10.  
  11. # 不需要加入缓存的类 
  12. targetNames=xxxRecordManager,xxxSetRecordManager,xxxStatisticsIdentificationManager 
  13. # 不需要缓存的方法 
  14. methodNames= 
  15.  
  16. #设置缓存失效时间 
  17. com.service.impl.xxxRecordManager= 60 
  18. com.service.impl.xxxSetRecordManager= 60 
  19. defaultCacheExpireTime=3600 
  20.  
  21. fep.local.cache.capacity =10000 

要扫这些properties文件,在application.xml加入如下配置

  1.  <!-- 引入properties配置文件 -->  
  2.  <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
  3.     <property name="locations"
  4.         <list> 
  5.            <value>classpath:properties/*.properties</value> 
  6.             <!--要是有多个配置文件,只需在这里继续添加即可 --> 
  7.         </list> 
  8.     </property> 
  9. </bean> 

3、一些工具类

(1)RedisUtil

上面的bean中,RedisUtil是用来缓存和去除数据的实例

  1. package com.mucfc.msm.common; 
  2.  
  3. import java.io.Serializable; 
  4. import java.util.Set; 
  5. import java.util.concurrent.TimeUnit; 
  6.  
  7. import org.apache.log4j.Logger; 
  8. import org.springframework.data.redis.core.RedisTemplate; 
  9. import org.springframework.data.redis.core.ValueOperations; 
  10.  
  11. /** 
  12. * redis cache 工具类 
  13. * 
  14. */ 
  15. public final class RedisUtil { 
  16. private Logger logger = Logger.getLogger(RedisUtil.class); 
  17. private RedisTemplate<Serializable, Object> redisTemplate; 
  18.  
  19. /** 
  20.   * 批量删除对应的value 
  21.   * 
  22.   * @param keys 
  23.   */ 
  24. public void remove(final String... keys) { 
  25.   for (String key : keys) { 
  26.    remove(key); 
  27.   } 
  28.  
  29. /** 
  30.   * 批量删除key 
  31.   * 
  32.   * @param pattern 
  33.   */ 
  34. public void removePattern(final String pattern) { 
  35.   Set<Serializable> keys = redisTemplate.keys(pattern); 
  36.   if (keys.size() > 0
  37.    redisTemplate.delete(keys); 
  38.  
  39. /** 
  40.   * 删除对应的value 
  41.   * 
  42.   * @param key 
  43.   */ 
  44. public void remove(final String key) { 
  45.   if (exists(key)) { 
  46.    redisTemplate.delete(key); 
  47.   } 
  48.  
  49. /** 
  50.   * 判断缓存中是否有对应的value 
  51.   * 
  52.   * @param key 
  53.   * @return 
  54.   */ 
  55. public boolean exists(final String key) { 
  56.   return redisTemplate.hasKey(key); 
  57.  
  58. /** 
  59.   * 读取缓存 
  60.   * 
  61.   * @param key 
  62.   * @return 
  63.   */ 
  64. public Object get(final String key) { 
  65.   Object result = null
  66.   ValueOperations<Serializable, Object> operations = redisTemplate 
  67.     .opsForValue(); 
  68.   result = operations.get(key); 
  69.   return result; 
  70.  
  71. /** 
  72.   * 写入缓存 
  73.   * 
  74.   * @param key 
  75.   * @param value 
  76.   * @return 
  77.   */ 
  78. public boolean set(final String key, Object value) { 
  79.   boolean result = false
  80.   try { 
  81.    ValueOperations<Serializable, Object> operations = redisTemplate 
  82.      .opsForValue(); 
  83.    operations.set(key, value); 
  84.    result = true
  85.   } catch (Exception e) { 
  86.    e.printStackTrace(); 
  87.   } 
  88.   return result; 
  89.  
  90. /** 
  91.   * 写入缓存 
  92.   * 
  93.   * @param key 
  94.   * @param value 
  95.   * @return 
  96.   */ 
  97. public boolean set(final String key, Object value, Long expireTime) { 
  98.   boolean result = false
  99.   try { 
  100.    ValueOperations<Serializable, Object> operations = redisTemplate 
  101.      .opsForValue(); 
  102.    operations.set(key, value); 
  103.    redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); 
  104.    result = true
  105.   } catch (Exception e) { 
  106.    e.printStackTrace(); 
  107.   } 
  108.   return result; 
  109.  
  110. public void setRedisTemplate( 
  111.    RedisTemplate<Serializable, Object> redisTemplate) { 
  112.   this.redisTemplate = redisTemplate; 

(2)MethodCacheInterceptor

切面MethodCacheInterceptor,这是用来给不同的方法来加入判断如果缓存存在数据,从缓存取数据。否则***次从数据库取,并将结果保存到缓存 中去。

  1. package com.mucfc.msm.common; 
  2.  
  3. import java.io.File; 
  4. import java.io.FileInputStream; 
  5. import java.io.InputStream; 
  6. import java.util.ArrayList; 
  7. import java.util.List; 
  8. import java.util.Properties; 
  9.  
  10. import org.aopalliance.intercept.MethodInterceptor; 
  11. import org.aopalliance.intercept.MethodInvocation; 
  12. import org.apache.log4j.Logger; 
  13.  
  14. public class MethodCacheInterceptor implements MethodInterceptor { 
  15. private Logger logger = Logger.getLogger(MethodCacheInterceptor.class); 
  16. private RedisUtil redisUtil; 
  17. private List<String> targetNamesList; // 不加入缓存的service名称 
  18. private List<String> methodNamesList; // 不加入缓存的方法名称 
  19. private Long defaultCacheExpireTime; // 缓存默认的过期时间 
  20. private Long xxxRecordManagerTime; // 
  21. private Long xxxSetRecordManagerTime; // 
  22.  
  23. /** 
  24.   * 初始化读取不需要加入缓存的类名和方法名称 
  25.   */ 
  26. public MethodCacheInterceptor() { 
  27.   try { 
  28.     File f = new File("D:\\lunaJee-workspace\\msm\\msm_core\\src\\main\\java\\com\\mucfc\\msm\\common\\cacheConf.properties"); 
  29.     //配置文件位置直接被写死,有需要自己修改下 
  30.        InputStream in = new FileInputStream(f); 
  31. //   InputStream in = getClass().getClassLoader().getResourceAsStream( 
  32. //     "D:\\lunaJee-workspace\\msm\\msm_core\\src\\main\\java\\com\\mucfc\\msm\\common\\cacheConf.properties"); 
  33.    Properties p = new Properties(); 
  34.    p.load(in); 
  35.    // 分割字符串 
  36.    String[] targetNames = p.getProperty("targetNames").split(","); 
  37.    String[] methodNames = p.getProperty("methodNames").split(","); 
  38.  
  39.    // 加载过期时间设置 
  40.    defaultCacheExpireTime = Long.valueOf(p.getProperty("defaultCacheExpireTime")); 
  41.    xxxRecordManagerTime = Long.valueOf(p.getProperty("com.service.impl.xxxRecordManager")); 
  42.    xxxSetRecordManagerTime = Long.valueOf(p.getProperty("com.service.impl.xxxSetRecordManager")); 
  43.    // 创建list 
  44.    targetNamesList = new ArrayList<String>(targetNames.length); 
  45.    methodNamesList = new ArrayList<String>(methodNames.length); 
  46.    Integer maxLen = targetNames.length > methodNames.length ? targetNames.length 
  47.      : methodNames.length; 
  48.    // 将不需要缓存的类名和方法名添加到list中 
  49.    for (int i = 0; i < maxLen; i++) { 
  50.     if (i < targetNames.length) { 
  51.      targetNamesList.add(targetNames[i]); 
  52.     } 
  53.     if (i < methodNames.length) { 
  54.      methodNamesList.add(methodNames[i]); 
  55.     } 
  56.    } 
  57.   } catch (Exception e) { 
  58.    e.printStackTrace(); 
  59.   } 
  60.  
  61. @Override 
  62. public Object invoke(MethodInvocation invocation) throws Throwable { 
  63.   Object value = null
  64.  
  65.   String targetName = invocation.getThis().getClass().getName(); 
  66.   String methodName = invocation.getMethod().getName(); 
  67.   // 不需要缓存的内容 
  68.   //if (!isAddCache(StringUtil.subStrForLastDot(targetName), methodName)) { 
  69.   if (!isAddCache(targetName, methodName)) { 
  70.    // 执行方法返回结果 
  71.    return invocation.proceed(); 
  72.   } 
  73.   Object[] arguments = invocation.getArguments(); 
  74.   String key = getCacheKey(targetName, methodName, arguments); 
  75.   System.out.println(key); 
  76.  
  77.   try { 
  78.    // 判断是否有缓存 
  79.    if (redisUtil.exists(key)) { 
  80.     return redisUtil.get(key); 
  81.    } 
  82.    // 写入缓存 
  83.    value = invocation.proceed(); 
  84.    if (value != null) { 
  85.     final String tkey = key; 
  86.     final Object tvalue = value; 
  87.     new Thread(new Runnable() { 
  88.      @Override 
  89.      public void run() { 
  90.       if (tkey.startsWith("com.service.impl.xxxRecordManager")) { 
  91.        redisUtil.set(tkey, tvalue, xxxRecordManagerTime); 
  92.       } else if (tkey.startsWith("com.service.impl.xxxSetRecordManager")) { 
  93.        redisUtil.set(tkey, tvalue, xxxSetRecordManagerTime); 
  94.       } else { 
  95.        redisUtil.set(tkey, tvalue, defaultCacheExpireTime); 
  96.       } 
  97.      } 
  98.     }).start(); 
  99.    } 
  100.   } catch (Exception e) { 
  101.    e.printStackTrace(); 
  102.    if (value == null) { 
  103.     return invocation.proceed(); 
  104.    } 
  105.   } 
  106.   return value; 
  107.  
  108. /** 
  109.   * 是否加入缓存 
  110.   * 
  111.   * @return 
  112.   */ 
  113. private boolean isAddCache(String targetName, String methodName) { 
  114.   boolean flag = true
  115.   if (targetNamesList.contains(targetName) 
  116.     || methodNamesList.contains(methodName)) { 
  117.    flag = false
  118.   } 
  119.   return flag; 
  120.  
  121. /** 
  122.   * 创建缓存key 
  123.   * 
  124.   * @param targetName 
  125.   * @param methodName 
  126.   * @param arguments 
  127.   */ 
  128. private String getCacheKey(String targetName, String methodName, 
  129.    Object[] arguments) { 
  130.   StringBuffer sbu = new StringBuffer(); 
  131.   sbu.append(targetName).append("_").append(methodName); 
  132.   if ((arguments != null) && (arguments.length != 0)) { 
  133.    for (int i = 0; i < arguments.length; i++) { 
  134.     sbu.append("_").append(arguments[i]); 
  135.    } 
  136.   } 
  137.   return sbu.toString(); 
  138.  
  139. public void setRedisUtil(RedisUtil redisUtil) { 
  140.   this.redisUtil = redisUtil; 

4、配置需要缓存的类或方法

在application.xml加入如下配置,有多个类或方法可以配置多个

  1. <!-- 需要加入缓存的类或方法 --> 
  2. <bean id="methodCachePointCut"  class="org.springframework.aop.support.RegexpMethodPointcutAdvisor" > 
  3.       <property name="advice" > 
  4.           <ref local="methodCacheInterceptor" /> 
  5.       </property> 
  6.       <property name="patterns" > 
  7.           <list> 
  8.            <!-- 确定正则表达式列表 --> 
  9.              <value>com\.mucfc\.msm\.service\.impl\...*ServiceImpl.*</value > 
  10.           </list> 
  11.       </property> 
  12. </bean > 

5、执行结果:

写了一个简单的单元测试如下:

  1. @Test 
  2.  public void getSettUnitBySettUnitIdTest() { 
  3.      String systemId = "CES"
  4.      String merchantId = "133"
  5.      SettUnit configSettUnit = settUnitService.getSettUnitBySettUnitId(systemId, merchantId, "ESP"); 
  6.      SettUnit configSettUnit1 = settUnitService.getSettUnitBySettUnitId(systemId, merchantId, "ESP"); 
  7.      boolean flag= (configSettUnit == configSettUnit1); 
  8.      System.out.println(configSettUnit); 
  9.      logger.info("查找结果" + configSettUnit.getBusinessType()); 
  10.  
  11.    //  localSecondFIFOCache.put("configSettUnit", configSettUnit.getBusinessType()); 
  12.   //  String string = localSecondFIFOCache.get("configSettUnit"); 
  13.        logger.info("查找结果" + string); 
  14.  } 

这是***次执行单元测试的过程:

MethodCacheInterceptor这个类中打了断点,然后每次查询前都会先进入这个方法

依次运行,发现没有缓存,所以会直接去查数据库

打印了出来的SQL语句:

第二次执行:

因为***次执行时,已经写入缓存了。所以第二次直接从缓存中取数据

3、取两次的结果进行地址的对比:

发现两个不是同一个对象,没错,是对的。如果是使用Ehcache的 话,那么二者的内存地址会是一样的。那是因为redis和ehcache使用的缓存机制是不一样的。ehcache是基于本地电脑的内存使用缓存,所以使 用缓存取数据时直接在本地电脑上取。转换成java对象就会是同一个内存地址,而redis它是在装有redis服务的电脑上(一般是另一台电脑),所以 取数据时经过传输到本地,会对应到不同的内存地址,所以用==来比较会返回false。但是它确实是从缓存中去取的,这点我们从上面的断点可以看到。

责任编辑:王雪燕 来源: 林炳文的专栏
相关推荐

2017-04-17 10:35:40

Spring BooRedis 操作

2009-07-17 17:16:48

Spring iBAT

2020-01-10 15:42:13

SpringBootRedis数据库

2020-08-19 08:55:47

Redis缓存数据库

2020-06-29 07:43:12

缓存RedisSpringBoot

2009-07-17 17:45:56

iBATIS Spri

2020-08-19 17:56:46

缓存Redis集中式

2017-05-09 08:27:42

分布式缓存技术Spring Redi

2023-10-12 08:00:48

2020-07-11 09:25:15

Python编程语言代码

2019-03-28 11:07:56

Spring BootRedis缓存

2023-05-05 18:38:33

多级缓存Caffeine开发

2018-09-12 19:46:53

数据库MySQLRedis

2014-12-31 09:56:29

Ehcache

2019-10-12 14:19:05

Redis数据库缓存

2023-03-10 13:33:00

缓存穿透缓存击穿缓存雪崩

2016-12-14 09:03:34

springhibernate异常

2021-11-10 11:37:48

Spring整合 Mybatis

2009-06-18 15:24:08

Spring OSGi

2009-06-19 10:00:37

Struts和Spri
点赞
收藏

51CTO技术栈公众号