成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

從零搭建Spring Boot腳手架:整合Redis作為緩存

存儲 存儲軟件 Redis
今天我們會把緩存也集成進來。緩存是一個系統應用必備的一種功能,除了在減輕數據庫的壓力之外。

[[338457]]

前言

 今天我們會把緩存也集成進來。緩存是一個系統應用必備的一種功能,除了在減輕數據庫的壓力之外。還在存儲一些短時效的數據場景中發揮著重大作用,比如存儲用戶Token、短信驗證碼等等,目前緩存的選型還是比較多的,EHCACHE、HAZELCAST、CAFFEINE、COUCHBASE以及本文要整合的REDIS。接下來我們將會在kono腳手架項目中集成Spring Cache以及Redis。

Gitee: https://gitee.com/felord/kono day05 分支

GitHub: https://github.com/NotFound403/kono day05 分支

2. 整合目標

使項目具有緩存功能,同時將默認的JDK序列化修改為Jackson序列化以存儲一些對象,同時實現一些特定的個性化的緩存空間以滿足不同場景下的不同緩存TTL時間需求。

3. 依賴集成

目前只需要引入下面的依賴即可:

  1.  <dependency> 
  2.     <groupId>org.springframework.boot</groupId> 
  3.     <artifactId>spring-boot-starter-data-redis</artifactId> 
  4. </dependency> 
  5. <dependency> 
  6.     <groupId>org.springframework.boot</groupId> 
  7.     <artifactId>spring-boot-starter-cache</artifactId> 
  8. </dependency> 
  9. <dependency> 
  10.     <groupId>org.apache.commons</groupId> 
  11.     <artifactId>commons-pool2</artifactId> 
  12. </dependency> 

默認情況下spring-data-redis使用高性能的lettuce客戶端實現,當然你可以替換為老舊的jedis。

4. 緩存及 Redis 配置

緩存以及Redis相關的配置項分別為spring.cache和spring.redis開頭的配置,這里比較簡單的配置為:

  1. spring: 
  2.   redis: 
  3.     host: localhost 
  4.     port: 6379 
  5.   cache: 
  6. #   type: REDIS 
  7.     redis: 
  8.     # 全局過期時間 
  9.       time-to-live: 120 

5. RedisTemplate 個性化

默認情況下會有兩個模板類被注入Spring IoC供我們使用,需要個性化配置來滿足實際的開發。

一個是RedisTemplate<Object, Object>,主要用于對象緩存,其默認使用JDK序列化,我們需要更改其序列化方式解決一些問題,比如Java 8日期問題、JSON序列化問題。需要我們重寫一下。

  1. /** 
  2.  * Redis的一些自定義配置. 
  3.  * 
  4.  * @author felord.cn 
  5.  * @since 2020 /8/17 20:39 
  6.  */ 
  7. @ConditionalOnClass(ObjectMapper.class) 
  8. @Configuration(proxyBeanMethods = false
  9. public class RedisConfiguration { 
  10.     /** 
  11.      * Redis template redis template. 
  12.      * 
  13.      * @param redisConnectionFactory the redis connection factory 
  14.      * @return the redis template 
  15.      */ 
  16.     @Bean("redisTemplate"
  17.     public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { 
  18.         RedisTemplate<Object, Object> template = new RedisTemplate<>(); 
  19.         template.setConnectionFactory(redisConnectionFactory); 
  20.         // 使用Jackson2JsonRedisSerialize 替換默認序列化 
  21.         Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = initJacksonSerializer(); 
  22.         // 設置value的序列化規則和 key的序列化規則 
  23.         template.setValueSerializer(jackson2JsonRedisSerializer); 
  24.         template.setKeySerializer(new StringRedisSerializer()); 
  25.         template.afterPropertiesSet(); 
  26.         return template; 
  27.     } 
  28.  
  29.     /** 
  30.      * 處理redis序列化問題 
  31.      * @return Jackson2JsonRedisSerializer 
  32.      */ 
  33.     private Jackson2JsonRedisSerializer<Object> initJacksonSerializer() { 
  34.         Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); 
  35.         ObjectMapper om = new ObjectMapper(); 
  36.         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 
  37.         //以下替代舊版本 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 
  38.         om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL); 
  39.         //bugFix Jackson2反序列化數據處理LocalDateTime類型時出錯 
  40.         om.disable(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS); 
  41.         // java8 時間支持 
  42.         om.registerModule(new JavaTimeModule()); 
  43.         jackson2JsonRedisSerializer.setObjectMapper(om); 
  44.         return jackson2JsonRedisSerializer; 
  45.     } 
  46.  

另一個是StringRedisTemplate,主要處理鍵值都是字符串的緩存,采用默認就好。

6. 緩存個性化

使用Spring Cache做緩存的時候,有針對不同的key設置不同過期時間的場景。比如Jwt Token我想設置為一周過期,而驗證碼我想設置為五分鐘過期。這個怎么實現呢?需要我們個性化配置RedisCacheManager。首先我通過枚舉來定義這些緩存及其TTL時間。例如:

  1. /** 
  2.  * 緩存定義枚舉 
  3.  * 
  4.  * @author felord.cn 
  5.  * @see cn.felord.kono.configuration.CacheConfiguration 
  6.  * @since 2020/8/17 21:40 
  7.  */ 
  8.  
  9. public enum CacheEnum { 
  10.  
  11.     /** 
  12.      * 用戶jwt token 緩存空間 ttl 7天 
  13.      */ 
  14.     JWT_TOKEN_CACHE("usrTkn", 7 * 24 * 60 * 60), 
  15.     /** 
  16.      * 驗證碼緩存 5分鐘ttl 
  17.      */ 
  18.     SMS_CAPTCHA_CACHE("smsCode", 5 * 60); 
  19.  
  20.     /** 
  21.      * 緩存名稱 
  22.      */ 
  23.     private final String cacheName; 
  24.     /** 
  25.      * 緩存過期秒數 
  26.      */ 
  27.     private final int ttlSecond; 
  28.  
  29.     CacheEnum(String cacheName, int ttlSecond) { 
  30.         this.cacheName = cacheName; 
  31.         this.ttlSecond = ttlSecond; 
  32.     } 
  33.  
  34.     public String cacheName() { 
  35.         return this.cacheName; 
  36.     } 
  37.  
  38.  
  39.     public int ttlSecond() { 
  40.         return this.ttlSecond; 
  41.     } 

這樣就能很清楚地描述個性化的緩存了。

然后我們通過向Spring IoC分別注入RedisCacheConfiguration和RedisCacheManagerBuilderCustomizer來個性化配置,你可以留意CacheEnum是如何工作的。如果你有其它的個性化需要也可以對這兩個配置類進行定制化。

  1. import cn.felord.kono.enumeration.CacheEnum; 
  2. import org.springframework.boot.autoconfigure.cache.CacheProperties; 
  3. import org.springframework.boot.autoconfigure.cache.RedisCacheManagerBuilderCustomizer; 
  4. import org.springframework.cache.annotation.EnableCaching; 
  5. import org.springframework.context.annotation.Bean; 
  6. import org.springframework.context.annotation.Configuration; 
  7. import org.springframework.data.redis.cache.RedisCacheConfiguration; 
  8. import org.springframework.data.redis.cache.RedisCacheManager; 
  9. import org.springframework.data.redis.core.RedisTemplate; 
  10. import org.springframework.data.redis.serializer.RedisSerializationContext; 
  11.  
  12. import java.time.Duration; 
  13. import java.util.EnumSet; 
  14. import java.util.stream.Collectors; 
  15.  
  16. /** 
  17.  * redis 緩存配置. 
  18.  * 
  19.  * @author felord.cn 
  20.  * @since 2020 /8/17 20:14 
  21.  */ 
  22. @EnableCaching 
  23. @Configuration 
  24. public class CacheConfiguration { 
  25.  
  26.  
  27.     /** 
  28.      * Redis cache configuration. 
  29.      * 
  30.      * @param redisTemplate the redis template 
  31.      * @return the redis cache configuration 
  32.      */ 
  33.     @Bean 
  34.     public RedisCacheConfiguration redisCacheConfiguration(RedisTemplate<Object, Object> redisTemplate, CacheProperties cacheProperties) { 
  35.          // 參見 spring.cache.redis 
  36.         CacheProperties.Redis redisProperties = cacheProperties.getRedis(); 
  37.  
  38.         RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() 
  39.                 // 緩存的序列化問題 
  40.                 .serializeValuesWith(RedisSerializationContext.SerializationPair 
  41.                         .fromSerializer(redisTemplate.getValueSerializer())); 
  42.  
  43.         if (redisProperties.getTimeToLive() != null) { 
  44.             // 全局 TTL 時間 
  45.             redisCacheConfiguration = redisCacheConfiguration.entryTtl(redisProperties.getTimeToLive()); 
  46.         } 
  47.         if (redisProperties.getKeyPrefix() != null) { 
  48.             // key 前綴值 
  49.             redisCacheConfiguration = redisCacheConfiguration.prefixCacheNameWith(redisProperties.getKeyPrefix()); 
  50.         } 
  51.         if (!redisProperties.isCacheNullValues()) { 
  52.             // 默認緩存null值 可以防止緩存穿透 
  53.             redisCacheConfiguration = redisCacheConfiguration.disableCachingNullValues(); 
  54.         } 
  55.         if (!redisProperties.isUseKeyPrefix()) { 
  56.             // 不使用key前綴 
  57.             redisCacheConfiguration = redisCacheConfiguration.disableKeyPrefix(); 
  58.         } 
  59.         return redisCacheConfiguration; 
  60.     } 
  61.  
  62.  
  63.     /** 
  64.      * Redis cache manager 個性化配置緩存過期時間. 
  65.      * @see RedisCacheManager,CacheEnum 
  66.      * @return the redis cache manager builder customizer 
  67.      */ 
  68.     @Bean 
  69.     public RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer(RedisCacheConfiguration redisCacheConfiguration) { 
  70.  
  71.         return builder -> builder.cacheDefaults(redisCacheConfiguration) 
  72.                 // 自定義的一些緩存配置初始化 主要是特定緩存及其ttl時間 
  73.                 .withInitialCacheConfigurations(EnumSet.allOf(CacheEnum.class).stream() 
  74.                         .collect(Collectors.toMap(CacheEnum::cacheName, 
  75.                                 cacheEnum -> redisCacheConfiguration.entryTtl(Duration.ofSeconds(cacheEnum.ttlSecond()))))); 
  76.     } 
  77.  

個性化的同時我們可以通過@EnableCaching開啟Spring Cache緩存支持。關于Spring Cache的細節可以通過文章Spring Cache 詳解來了解。

 

驗證Spring Cache Redis緩存個性化

 

請注意,只有通過Spring Cache操作緩存才會達到上圖的效果。命令行操作需要顯式的聲明指令。

7. 總結

最近事情比較多,所以難得抽出時間來搞一搞。如果你在實際開發中遇到需要整合的功能也可以告訴我,同時如果你發現整合中的一些缺陷或者 Bug 請提交 ISSUE。多多關注:碼農小胖哥,跟我一起整合開發腳手架。

 本文轉載自微信公眾號「碼農小胖哥」,可以通過以下二維碼關注。轉載本文請聯系碼農小胖哥公眾號。碼農小胖哥  

 

責任編輯:武曉燕 來源: 碼農小胖哥
相關推薦

2021-07-13 18:42:38

Spring Boot腳手架開發

2021-09-01 10:07:43

開發零搭建Groovy

2021-03-09 17:11:09

數據庫腳手架開發

2021-04-28 16:10:48

開發腳手架 Spring

2021-03-11 14:16:47

Spring Boo開發腳手架

2021-07-29 18:49:49

Spring開發腳手架

2021-05-13 17:02:38

MDC腳手架日志

2021-04-13 14:47:53

認證授權Java

2023-11-21 17:36:04

OpenFeignSentinel

2025-05-16 07:24:41

Springkafka腳手架

2021-04-20 19:24:16

腳手架 Java微信

2020-06-29 11:35:02

Spring BootJava腳手架

2016-08-10 14:59:41

前端Javascript工具

2021-06-02 17:58:49

腳手架 冪等性前端

2021-02-19 22:43:50

開發腳手架Controller

2017-04-17 10:35:40

Spring BooRedis 操作

2021-01-07 05:34:07

腳手架JDK緩存

2022-07-18 07:58:46

Spring工具工具類

2021-12-23 10:35:32

SpringCloud腳手架架構

2016-09-07 15:35:06

VueReact腳手架
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 久久久久亚洲精品 | 国产三级一区二区 | 国产精品久久久久久久久久免费看 | 中文字幕第三页 | 日韩一区二区福利 | 国产精品久久久久久久久久久久 | 三级黄色大片网站 | 中文字幕一区二区三区四区五区 | 久久免费精品 | 久久久久亚洲 | aaa在线| 二区三区在线观看 | 午夜一级大片 | 一区二区三区视频播放 | 日韩精品一区二区三区久久 | 久久国产精品视频 | 国产一区二区三区在线视频 | 国产98在线 | 免费, | 午夜一区二区三区在线观看 | 午夜精品久久久久久久久久久久久 | 日韩av美女电影 | 国产区一区二区三区 | 亚洲国产精品一区二区久久 | 国产高清亚洲 | 一区二区三区亚洲 | av网站在线免费观看 | 亚洲国产精品成人久久久 | 精品久久一区 | 久久大陆 | 美女国产一区 | 91久久久久久久久久久久久 | 午夜影院视频 | 久久久久久久久91 | 国产日韩一区二区三免费 | 亚洲天堂av网 | 久久一区视频 | 拍拍无遮挡人做人爱视频免费观看 | 久久久久久成人 | 一区欧美| 一级做a爰片性色毛片16 | 视频一区二区在线观看 |