Spring Boot 2.x基礎(chǔ)教程:使用集中式緩存Redis
點(diǎn)擊上方藍(lán)色“程序猿DD”,選擇“設(shè)為星標(biāo)”
回復(fù)“資源”獲取獨(dú)家整理的學(xué)習(xí)資料!

之前我們介紹了兩種進(jìn)程內(nèi)緩存的用法,包括Spring Boot默認(rèn)使用的ConcurrentMap緩存以及緩存框架EhCache。雖然EhCache已經(jīng)能夠適用很多應(yīng)用場(chǎng)景,但是由于EhCache是進(jìn)程內(nèi)的緩存框架,在集群模式下時(shí),各應(yīng)用服務(wù)器之間的緩存都是獨(dú)立的,因此在不同服務(wù)器的進(jìn)程間會(huì)存在緩存不一致的情況。即使EhCache提供了集群環(huán)境下的緩存同步策略,但是同步依然是需要一定的時(shí)間,短暫的緩存不一致依然存在。
在一些要求高一致性(任何數(shù)據(jù)變化都能及時(shí)的被查詢到)的系統(tǒng)和應(yīng)用中,就不能再使用EhCache來(lái)解決了,這個(gè)時(shí)候使用集中式緩存就可以很好的解決緩存數(shù)據(jù)的一致性問(wèn)題。接下來(lái)我們就來(lái)學(xué)習(xí)一下,如何在Spring Boot的緩存支持中使用Redis實(shí)現(xiàn)數(shù)據(jù)緩存。
動(dòng)手試試
本篇的實(shí)現(xiàn)將基于上一篇的基礎(chǔ)工程來(lái)進(jìn)行。先來(lái)回顧下上一篇中的程序要素:
User實(shí)體的定義
@Entity
@Data
@NoArgsConstructor
public?class?User?implements?Serializable?{
????@Id
????@GeneratedValue
????private?Long?id;
????private?String?name;
????private?Integer?age;
????public?User(String?name,?Integer?age)?{
????????this.name?=?name;
????????this.age?=?age;
????}
}
User實(shí)體的數(shù)據(jù)訪問(wèn)實(shí)現(xiàn)(涵蓋了緩存注解)
@CacheConfig(cacheNames?=?"users")
public?interface?UserRepository?extends?JpaRepository<User,?Long>?{
????@Cacheable
????User?findByName(String?name);
}
下面開始改造這個(gè)項(xiàng)目:
第一步:pom.xml中增加相關(guān)依賴:
<dependency>
????<groupId>org.springframework.bootgroupId>
????<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
<dependency>
????<groupId>org.apache.commonsgroupId>
????<artifactId>commons-pool2artifactId>
dependency>
在Spring Boot 1.x的早期版本中,該依賴的名稱為
spring-boot-starter-redis,所以在Spring Boot 1.x基礎(chǔ)教程中與這里不同。
第二步:配置文件中增加配置信息,以本地運(yùn)行為例,比如:
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.shutdown-timeout=100ms
關(guān)于連接池的配置,注意幾點(diǎn):
Redis的連接池配置在1.x版本中前綴為 spring.redis.pool與Spring Boot 2.x有所不同。在1.x版本中采用jedis作為連接池,而在2.x版本中采用了lettuce作為連接池 以上配置均為默認(rèn)值,實(shí)際上生產(chǎn)需進(jìn)一步根據(jù)部署情況與業(yè)務(wù)要求做適當(dāng)修改.
再來(lái)試試單元測(cè)試:
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public?class?Chapter54ApplicationTests?{
????@Autowired
????private?UserRepository?userRepository;
????@Autowired
????private?CacheManager?cacheManager;
????@Test
????public?void?test()?throws?Exception?{
????????System.out.println("CacheManager?type?:?"?+?cacheManager.getClass());
????????//?創(chuàng)建1條記錄
????????userRepository.save(new?User("AAA",?10));
????????User?u1?=?userRepository.findByName("AAA");
????????System.out.println("第一次查詢:"?+?u1.getAge());
????????User?u2?=?userRepository.findByName("AAA");
????????System.out.println("第二次查詢:"?+?u2.getAge());
????}
}
執(zhí)行測(cè)試輸出可以得到:
CacheManager?type?:?class?org.springframework.data.redis.cache.RedisCacheManager
Hibernate:?select?next_val?as?id_val?from?hibernate_sequence?for?update
Hibernate:?update?hibernate_sequence?set?next_val=???where?next_val=?
Hibernate:?insert?into?user?(age,?name,?id)?values?(?,??,??)
2020-08-12?16:25:26.954??INFO?68282?---?[???????????main]?io.lettuce.core.EpollProvider????????????:?Starting?without?optional?epoll?library
2020-08-12?16:25:26.955??INFO?68282?---?[???????????main]?io.lettuce.core.KqueueProvider???????????:?Starting?without?optional?kqueue?library
Hibernate:?select?user0_.id?as?id1_0_,?user0_.age?as?age2_0_,?user0_.name?as?name3_0_?from?user?user0_?where?user0_.name=?
第一次查詢:10
第二次查詢:10
可以看到:
第一行輸出的CacheManager type為 org.springframework.data.redis.cache.RedisCacheManager,而不是上一篇中的EhCacheCacheManager了第二次查詢的時(shí)候,沒有輸出SQL語(yǔ)句,所以是走的緩存獲取
整合成功!
思考題
既然EhCache等進(jìn)程內(nèi)緩存有一致性問(wèn)題存在,而Redis性能好而且還能解決一致性問(wèn)題,那么我們只要學(xué)會(huì)用Redis就好了咯,為什么還要學(xué)進(jìn)程內(nèi)緩存呢?先留下你的思考,下一篇我們一起討論這個(gè)問(wèn)題!歡迎關(guān)注本系列教程:http://blog.didispace.com/spring-boot-learning-2x/
代碼示例
本文的相關(guān)例子可以查看下面?zhèn)}庫(kù)中的chapter5-4目錄:
Github:https://github.com/dyc87112/SpringBoot-Learning/ Gitee:https://gitee.com/didispace/SpringBoot-Learning/
如果您覺得本文不錯(cuò),歡迎Star支持,您的關(guān)注是我堅(jiān)持的動(dòng)力!
往期推薦
我在星球與你分享經(jīng)驗(yàn)、交流成長(zhǎng)
???????



