Java SpringCache+Redis緩存數(shù)據(jù)詳解
前言
這幾天學(xué)習(xí)谷粒商城又再次的回顧了一次SpringCache,之前在學(xué)習(xí)谷粒學(xué)院的時候其實已經(jīng)學(xué)習(xí)了一次了?。?!
這里就對自己學(xué)過來的內(nèi)容進(jìn)行一次的總結(jié)和歸納!?。?/p>
一、什么是SpringCache
- Spring Cache 是一個非常優(yōu)秀的緩存組件。自Spring 3.1起,提供了類似于@Transactional注解事務(wù)的注解Cache支持,且提供了Cache抽象,方便切換各種底層Cache(如:redis)
- 使用Spring Cache的好處:
- 提供基本的Cache抽象,方便切換各種底層Cache;
- 通過注解Cache可以實現(xiàn)類似于事務(wù)一樣,緩存邏輯透明的應(yīng)用到我們的業(yè)務(wù)代碼上,且只需要更少的代碼就可以完成;
- 提供事務(wù)回滾時也自動回滾緩存;
- 支持比較復(fù)雜的緩存邏輯;
二、項目集成Spring Cache + Redis
- 依賴
<!-- redis --> <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>
開啟@EnableCaching
1、配置方式
①第一種:配置類
@Configuration @EnableCaching public class RedisConfig { /** * 自定義key規(guī)則 * @return */ @Bean public KeyGenerator keyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... params) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); } }; } /** * 設(shè)置RedisTemplate規(guī)則 * @param redisConnectionFactory * @return */ @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); //解決查詢緩存轉(zhuǎn)換異常的問題 ObjectMapper om = new ObjectMapper(); // 指定要序列化的域,field,get和set,以及修飾符范圍,ANY是都有包括private和public om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // 指定序列化輸入的類型,類必須是非final修飾的,final修飾的類,比如String,Integer等會跑出異常 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); //序列號key value redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } /** * 設(shè)置CacheManager緩存規(guī)則 * @param factory * @return */ @Bean public CacheManager cacheManager(RedisConnectionFactory factory) { RedisSerializer<String> redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); //解決查詢緩存轉(zhuǎn)換異常的問題 ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // 配置序列化(解決亂碼的問題),過期時間600秒 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofSeconds(600)) .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) .disableCachingNullValues(); RedisCacheManager cacheManager = RedisCacheManager.builder(factory) .cacheDefaults(config) .build(); return cacheManager; } }
或
②結(jié)合配置+配置文件
spring: cache: #指定緩存類型為redis type: redis redis: # 指定redis中的過期時間為1h time-to-live: 3600000 key-prefix: CACHE_ #緩存key前綴 use-key-prefix: true #是否開啟緩存key前綴 cache-null-values: true #緩存空值,解決緩存穿透問題
默認(rèn)使用jdk進(jìn)行序列化(可讀性差),默認(rèn)ttl為-1永不過期,自定義序列化方式為JSON需要編寫配置類
@Configuration @EnableConfigurationProperties(CacheProperties.class)//拿到Redis在配置文件的配置 public class MyCacheConfig { @Bean public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) { //獲取到配置文件中的配置信息 CacheProperties.Redis redisProperties = cacheProperties.getRedis(); org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration.defaultCacheConfig(); //指定緩存序列化方式為json config = config.serializeValuesWith( RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); //設(shè)置配置文件中的各項配置,如過期時間 if (redisProperties.getTimeToLive() != null) { config = config.entryTtl(redisProperties.getTimeToLive()); } if (redisProperties.getKeyPrefix() != null) { config = config.prefixKeysWith(redisProperties.getKeyPrefix()); } if (!redisProperties.isCacheNullValues()) { config = config.disableCachingNullValues(); } if (!redisProperties.isUseKeyPrefix()) { config = config.disableKeyPrefix(); } return config; } }
說明:
第一種,全自定義配置第二種,簡單配置+自定義配置value值json轉(zhuǎn)義
- 對redis進(jìn)行配置
#redis配置 spring.redis.host=47.120.237.184 spring.redis.port=6379 spring.redis.password=ach2ng@123356 spring.redis.database= 0 spring.redis.timeout=1800000 #redis池設(shè)置 spring.redis.lettuce.pool.max-active=20 spring.redis.lettuce.pool.max-wait=-1 #最大阻塞等待時間(負(fù)數(shù)表示沒限制) spring.redis.lettuce.pool.max-idle=5 spring.redis.lettuce.pool.min-idle=0
三、使用Spring Cache
@Cacheable
根據(jù)方法對其返回結(jié)果進(jìn)行緩存,下次請求時,如果緩存存在,則直接讀取緩存數(shù)據(jù)返回;如果緩存不存在,則執(zhí)行方法,并把返回的結(jié)果存入緩存中。一般用在查詢方法上。
屬性/方法名 | 解釋 |
---|---|
value | 緩存名,必填,它指定了你的緩存存放在哪塊分區(qū),可多指定,如{"catagory","xxxx",....} |
cacheNames | 與 value 差不多,二選一即可 |
key | 可選屬性,可以使用 SpEL 標(biāo)簽自定義緩存的key,如:#root.methodName【用方法名作為key】 |
sync | 默認(rèn)false,為true時,會讓操作被同步保護(hù),可避免緩存擊穿問題 |
@CachePut
使用該注解標(biāo)志的方法,每次都會執(zhí)行,并將結(jié)果存入指定的緩存中。其他方法可以直接從響應(yīng)的緩存中讀取緩存數(shù)據(jù),而不需要再去查詢數(shù)據(jù)庫。一般用在新增方法上。
屬性/方法名 | |
---|---|
value | 緩存名,必填,它指定了你的緩存存放在==哪塊分區(qū),==可多指定,如{"catagory","xxxx",....} |
cacheNames | 與 value 差不多,二選一即可 |
key | 可選屬性,可以使用 SpEL 標(biāo)簽自定義緩存的key |
@CacheEvict
使用該注解標(biāo)志的方法,會清空指定的緩存。一般用在更新或者刪除方法上
屬性/方法名 | 解釋 |
---|---|
value | 緩存名,必填,它指定了你的緩存存放在==哪塊分區(qū),==可多指定,如{"catagory","xxxx",....} |
cacheNames | 與 value 差不多,二選一即可 |
key | 可選屬性,可以使用 SpEL 標(biāo)簽自定義緩存的key key如果是字符串"''",【請加上單引號】 |
allEntries | 是否清空所有緩存,默認(rèn)為 false。如果指定為 true,則方法調(diào)用后將立即清空所有的緩存 allEntries = true,會對刪除value分區(qū)里的所有數(shù)據(jù) |
beforeInvocation | 是否在方法執(zhí)行前就清空,默認(rèn)為 false。如果指定為 true,則在方法執(zhí)行前就會清空緩存 |
@Caching
可組合使用以上注解,如:
//組合了刪除緩存的@CacheEvict注解,同時刪除兩個 @Cacheing(evict= {@CacheEvict(value="a"),key="'getLists'"}), {@CacheEvict(value="b"),key="'getArr'"}) )
使用舉例 失效模式: 更新操作后,刪除緩存 雙寫模式: 更新操作后,新增緩存,掩蓋
四、SpringCache原理與不足
1、讀模式
緩存穿透:
查詢一個null數(shù)據(jù)。
解決方案:緩存空數(shù)據(jù)
可通過spring.cache.redis.cache-null-values=true
緩存擊穿:
大量并發(fā)進(jìn)來同時查詢一個正好過期的數(shù)據(jù)。
解決方案: 加鎖 ? 默認(rèn)是無加鎖的;
使用sync = true
來解決擊穿問題
緩存雪崩:
大量的key同時過期。
解決方案:加隨機(jī)時間,time-to-live: 3600000。
2、寫模式:(緩存與數(shù)據(jù)庫一致)
- 讀寫加鎖。
- 引入Canal,感知到MySQL的更新去更新Redis
- 讀多寫多,直接去數(shù)據(jù)庫查詢就行
五、總結(jié)
常規(guī)數(shù)據(jù)(讀多寫少,即時性,一致性要求不高的數(shù)據(jù),完全可以使用Spring-Cache):
寫模式(只要緩存的數(shù)據(jù)有過期時間就足夠了)
特殊數(shù)據(jù):
特殊設(shè)計(讀寫鎖、redis分布鎖等
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
BeanPostProcessor在顯示調(diào)用初始化方法前修改bean詳解
這篇文章主要介紹了BeanPostProcessor在顯示調(diào)用初始化方法前修改bean詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12Java實現(xiàn)的簡單字符串反轉(zhuǎn)操作示例
這篇文章主要介紹了Java實現(xiàn)的簡單字符串反轉(zhuǎn)操作,結(jié)合實例形式分別描述了java遍歷逆序輸出以及使用StringBuffer類的reverse()方法兩種字符串反轉(zhuǎn)操作技巧,需要的朋友可以參考下2018-08-08詳解Java并發(fā)工具類之CountDownLatch和CyclicBarrier
在JDK的并發(fā)包中,有幾個非常有用的并發(fā)工具類,它們分別是:CountDownLatch、CyclicBarrier、Semaphore和Exchanger,本文主要來講講其中CountDownLatch和CyclicBarrier的使用,感興趣的可以了解一下2023-06-06