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