上一文咱們整合了Mybatis Plus,今天咱們會把緩存也集成進來。緩存是一個系統應用必備的一種功能,除了在減輕數據庫的壓力以外。還在存儲一些短時效的數據場景中發揮着重大做用,好比存儲用戶Token、短信驗證碼等等,目前緩存的選型仍是比較多的,EHCACHE、HAZELCAST、CAFFEINE、COUCHBASE以及本文要整合的REDIS。接下來咱們將會在kono腳手架項目中集成Spring Cache以及Redis。html
Gitee: https://gitee.com/felord/kono day05 分支GitHub: https://github.com/NotFound40... day05 分支java
使項目具備緩存功能,同時將默認的JDK序列化修改成Jackson序列化以存儲一些對象,同時實現一些特定的個性化的緩存空間以知足不一樣場景下的不一樣緩存TTL時間需求。git
目前只須要引入下面的依賴便可:github
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency>
默認狀況下spring-data-redis使用高性能的lettuce客戶端實現,固然你能夠替換爲老舊的jedis。redis
緩存以及Redis相關的配置項分別爲spring.cache
和spring.redis
開頭的配置,這裏比較簡單的配置爲:spring
spring: redis: host: localhost port: 6379 cache: # type: REDIS redis: # 全局過時時間 time-to-live: 120
默認狀況下會有兩個模板類被注入Spring IoC供咱們使用,須要個性化配置來知足實際的開發。數據庫
一個是RedisTemplate<Object, Object>
,主要用於對象緩存,其默認使用JDK序列化,咱們須要更改其序列化方式解決一些問題,好比Java 8日期問題、JSON序列化問題。須要咱們重寫一下。apache
/** * Redis的一些自定義配置. * * @author felord.cn * @since 2020 /8/17 20:39 */ @ConditionalOnClass(ObjectMapper.class) @Configuration(proxyBeanMethods = false) public class RedisConfiguration { /** * Redis template redis template. * * @param redisConnectionFactory the redis connection factory * @return the redis template */ @Bean("redisTemplate") public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory); // 使用Jackson2JsonRedisSerialize 替換默認序列化 Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = initJacksonSerializer(); // 設置value的序列化規則和 key的序列化規則 template.setValueSerializer(jackson2JsonRedisSerializer); template.setKeySerializer(new StringRedisSerializer()); template.afterPropertiesSet(); return template; } /** * 處理redis序列化問題 * @return Jackson2JsonRedisSerializer */ private Jackson2JsonRedisSerializer<Object> initJacksonSerializer() { Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); //如下替代舊版本 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL); //bugFix Jackson2反序列化數據處理LocalDateTime類型時出錯 om.disable(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS); // java8 時間支持 om.registerModule(new JavaTimeModule()); jackson2JsonRedisSerializer.setObjectMapper(om); return jackson2JsonRedisSerializer; } }
另外一個是StringRedisTemplate
,主要處理鍵值都是字符串的緩存,採用默認就好。緩存
使用Spring Cache作緩存的時候,有針對不一樣的key設置不一樣過時時間的場景。好比Jwt Token我想設置爲一週過時,而驗證碼我想設置爲五分鐘過時。這個怎麼實現呢?須要咱們個性化配置RedisCacheManager
。首先我經過枚舉來定義這些緩存及其TTL時間。例如:app
/** * 緩存定義枚舉 * * @author felord.cn * @see cn.felord.kono.configuration.CacheConfiguration * @since 2020/8/17 21:40 */ public enum CacheEnum { /** * 用戶jwt token 緩存空間 ttl 7天 */ JWT_TOKEN_CACHE("usrTkn", 7 * 24 * 60 * 60), /** * 驗證碼緩存 5分鐘ttl */ SMS_CAPTCHA_CACHE("smsCode", 5 * 60); /** * 緩存名稱 */ private final String cacheName; /** * 緩存過時秒數 */ private final int ttlSecond; CacheEnum(String cacheName, int ttlSecond) { this.cacheName = cacheName; this.ttlSecond = ttlSecond; } public String cacheName() { return this.cacheName; } public int ttlSecond() { return this.ttlSecond; } }
這樣就能很清楚地描述個性化的緩存了。
而後咱們經過向Spring IoC分別注入RedisCacheConfiguration
和RedisCacheManagerBuilderCustomizer
來個性化配置,你能夠留意CacheEnum
是如何工做的。若是你有其它的個性化須要也能夠對這兩個配置類進行定製化。
import cn.felord.kono.enumeration.CacheEnum; import org.springframework.boot.autoconfigure.cache.CacheProperties; import org.springframework.boot.autoconfigure.cache.RedisCacheManagerBuilderCustomizer; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.RedisSerializationContext; import java.time.Duration; import java.util.EnumSet; import java.util.stream.Collectors; /** * redis 緩存配置. * * @author felord.cn * @since 2020 /8/17 20:14 */ @EnableCaching @Configuration public class CacheConfiguration { /** * Redis cache configuration. * * @param redisTemplate the redis template * @return the redis cache configuration */ @Bean public RedisCacheConfiguration redisCacheConfiguration(RedisTemplate<Object, Object> redisTemplate, CacheProperties cacheProperties) { // 參見 spring.cache.redis CacheProperties.Redis redisProperties = cacheProperties.getRedis(); RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() // 緩存的序列化問題 .serializeValuesWith(RedisSerializationContext.SerializationPair .fromSerializer(redisTemplate.getValueSerializer())); if (redisProperties.getTimeToLive() != null) { // 全局 TTL 時間 redisCacheConfiguration = redisCacheConfiguration.entryTtl(redisProperties.getTimeToLive()); } if (redisProperties.getKeyPrefix() != null) { // key 前綴值 redisCacheConfiguration = redisCacheConfiguration.prefixCacheNameWith(redisProperties.getKeyPrefix()); } if (!redisProperties.isCacheNullValues()) { // 默認緩存null值 能夠防止緩存穿透 redisCacheConfiguration = redisCacheConfiguration.disableCachingNullValues(); } if (!redisProperties.isUseKeyPrefix()) { // 不使用key前綴 redisCacheConfiguration = redisCacheConfiguration.disableKeyPrefix(); } return redisCacheConfiguration; } /** * Redis cache manager 個性化配置緩存過時時間. * @see RedisCacheManager,CacheEnum * @return the redis cache manager builder customizer */ @Bean public RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer(RedisCacheConfiguration redisCacheConfiguration) { return builder -> builder.cacheDefaults(redisCacheConfiguration) // 自定義的一些緩存配置初始化 主要是特定緩存及其ttl時間 .withInitialCacheConfigurations(EnumSet.allOf(CacheEnum.class).stream() .collect(Collectors.toMap(CacheEnum::cacheName, cacheEnum -> redisCacheConfiguration.entryTtl(Duration.ofSeconds(cacheEnum.ttlSecond()))))); } }
個性化的同時咱們能夠經過註解@EnableCaching
開啓Spring Cache緩存支持。關於Spring Cache的細節能夠經過文章Spring Cache詳解來了解。
請注意,只有經過 Spring Cache操做緩存纔會達到上圖的效果。命令行操做須要顯式的聲明指令。
最近事情比較多,因此可貴抽出時間來搞一搞。若是你在實際開發中遇到須要整合的功能也能夠告訴我,同時若是你發現整合中的一些缺陷或者Bug請提交ISSUE。多多關注:碼農小胖哥,跟我一塊兒整合開發腳手架。
關注公衆號:Felordcn 獲取更多資訊