自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Redis整合Spring結(jié)合使用緩存實(shí)例

開發(fā) 前端 Redis
本文介紹了如何在Spring中配置redis,并通過Spring中AOP的思想,將緩存的方法切入到有需要進(jìn)入緩存的類或方法前面。

一、Redis介紹

什么是Redis?

redis是一個key-value存儲系統(tǒng)。和Memcached類似,它支持存儲的value類型相對更多,包括string(字符串)、 list(鏈表)、set(集合)、zset(sorted set –有序集合)和hash(哈希類型)。這些數(shù)據(jù)類型都支持push/pop、add/remove及取交集并集和差集及更豐富的操作,而且這些操作都是原 子性的。在此基礎(chǔ)上,redis支持各種不同方式的排序。與memcached一樣,為了保證效率,數(shù)據(jù)都是緩存在內(nèi)存中。區(qū)別的是redis會周期性的 把更新的數(shù)據(jù)寫入磁盤或者把修改操作寫入追加的記錄文件,并且在此基礎(chǔ)上實(shí)現(xiàn)了master-slave(主從)同步。

它有什么特點(diǎn)?

(1)Redis數(shù)據(jù)庫完全在內(nèi)存中,使用磁盤僅用于持久性。
(2)相比許多鍵值數(shù)據(jù)存儲,Redis擁有一套較為豐富的數(shù)據(jù)類型。
(3)Redis可以將數(shù)據(jù)復(fù)制到任意數(shù)量的從服務(wù)器。

Redis 優(yōu)勢?

(1)異常快速:Redis的速度非??欤棵肽軋?zhí)行約11萬集合,每秒約81000+條記錄。
(2)支持豐富的數(shù)據(jù)類型:Redis支持***多數(shù)開發(fā)人員已經(jīng)知道像列表,集合,有序集合,散列數(shù)據(jù)類型。這使得它非常容易解決各種各樣的問題,因?yàn)槲覀冎滥男﹩栴}是可以處理通過它的數(shù)據(jù)類型更好。
(3)操作都是原子性:所有Redis操作是原子的,這保證了如果兩個客戶端同時訪問的Redis服務(wù)器將獲得更新后的值。
(4)多功能實(shí)用工具:Redis是一個多實(shí)用的工具,可以在多個用例如緩存,消息,隊列使用(Redis原生支持發(fā)布/訂閱),任何短暫的數(shù)據(jù),應(yīng)用程序,如Web應(yīng)用程序會話,網(wǎng)頁***計數(shù)等。

Redis 缺點(diǎn)?

(1)單線程

(2)耗內(nèi)存

二、使用實(shí)例

本文使用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服務(wù)器中心 --> 
  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一些配置數(shù)據(jù)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. #設(shè)置緩存失效時間 
  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.             <!--要是有多個配置文件,只需在這里繼續(xù)添加即可 --> 
  7.         </list> 
  8.     </property> 
  9. </bean> 

3、一些工具類

(1)RedisUtil

上面的bean中,RedisUtil是用來緩存和去除數(shù)據(jù)的實(shí)例

  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.   * 批量刪除對應(yīng)的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.   * 刪除對應(yīng)的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.   * 判斷緩存中是否有對應(yīng)的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,這是用來給不同的方法來加入判斷如果緩存存在數(shù)據(jù),從緩存取數(shù)據(jù)。否則***次從數(shù)據(jù)庫取,并將結(jié)果保存到緩存 中去。

  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; // 緩存默認(rèn)的過期時間 
  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.    // 加載過期時間設(shè)置 
  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.    // 創(chuàng)建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.   // 不需要緩存的內(nèi)容 
  68.   //if (!isAddCache(StringUtil.subStrForLastDot(targetName), methodName)) { 
  69.   if (!isAddCache(targetName, methodName)) { 
  70.    // 執(zhí)行方法返回結(jié)果 
  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.   * 創(chuàng)建緩存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.            <!-- 確定正則表達(dá)式列表 --> 
  9.              <value>com\.mucfc\.msm\.service\.impl\...*ServiceImpl.*</value > 
  10.           </list> 
  11.       </property> 
  12. </bean > 

5、執(zhí)行結(jié)果:

寫了一個簡單的單元測試如下:

  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("查找結(jié)果" + configSettUnit.getBusinessType()); 
  10.  
  11.    //  localSecondFIFOCache.put("configSettUnit", configSettUnit.getBusinessType()); 
  12.   //  String string = localSecondFIFOCache.get("configSettUnit"); 
  13.        logger.info("查找結(jié)果" + string); 
  14.  } 

這是***次執(zhí)行單元測試的過程:

MethodCacheInterceptor這個類中打了斷點(diǎn),然后每次查詢前都會先進(jìn)入這個方法

依次運(yùn)行,發(fā)現(xiàn)沒有緩存,所以會直接去查數(shù)據(jù)庫

打印了出來的SQL語句:

第二次執(zhí)行:

因?yàn)?**次執(zhí)行時,已經(jīng)寫入緩存了。所以第二次直接從緩存中取數(shù)據(jù)

3、取兩次的結(jié)果進(jìn)行地址的對比:

發(fā)現(xiàn)兩個不是同一個對象,沒錯,是對的。如果是使用Ehcache的 話,那么二者的內(nèi)存地址會是一樣的。那是因?yàn)閞edis和ehcache使用的緩存機(jī)制是不一樣的。ehcache是基于本地電腦的內(nèi)存使用緩存,所以使 用緩存取數(shù)據(jù)時直接在本地電腦上取。轉(zhuǎn)換成java對象就會是同一個內(nèi)存地址,而redis它是在裝有redis服務(wù)的電腦上(一般是另一臺電腦),所以 取數(shù)據(jù)時經(jīng)過傳輸?shù)奖镜兀瑫?yīng)到不同的內(nèi)存地址,所以用==來比較會返回false。但是它確實(shí)是從緩存中去取的,這點(diǎn)我們從上面的斷點(diǎn)可以看到。

責(zé)任編輯:王雪燕 來源: 林炳文的專欄
相關(guān)推薦

2017-04-17 10:35:40

Spring BooRedis 操作

2009-07-17 17:16:48

Spring iBAT

2020-01-10 15:42:13

SpringBootRedis數(shù)據(jù)庫

2020-08-19 08:55:47

Redis緩存數(shù)據(jù)庫

2020-06-29 07:43:12

緩存RedisSpringBoot

2009-07-17 17:45:56

iBATIS Spri

2024-08-26 09:15:55

RedissonMyBatisSpring

2025-03-26 03:25:00

SpringGuavaCaffeine

2020-08-19 17:56:46

緩存Redis集中式

2023-10-12 08:00:48

2017-05-09 08:27:42

分布式緩存技術(shù)Spring Redi

2020-07-11 09:25:15

Python編程語言代碼

2025-02-21 12:00:00

SpringBoot防重復(fù)提交緩存機(jī)制

2019-03-28 11:07:56

Spring BootRedis緩存

2023-05-05 18:38:33

多級緩存Caffeine開發(fā)

2018-09-12 19:46:53

數(shù)據(jù)庫MySQLRedis

2014-12-31 09:56:29

Ehcache

2024-04-29 18:55:16

緩存Spring性能

2023-03-10 13:33:00

緩存穿透緩存擊穿緩存雪崩

2019-10-12 14:19:05

Redis數(shù)據(jù)庫緩存
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號