1. 程式人生 > >Spring Boot 2.x基礎教程:使用集中式快取Redis

Spring Boot 2.x基礎教程:使用集中式快取Redis

之前我們介紹了兩種程序內快取的用法,包括Spring Boot預設使用的[ConcurrentMap快取](http://blog.didispace.com/spring-boot-learning-21-5-1/)以及[快取框架EhCache](http://blog.didispace.com/spring-boot-learning-21-5-2/)。雖然EhCache已經能夠適用很多應用場景,但是由於EhCache是程序內的快取框架,在叢集模式下時,各應用伺服器之間的快取都是獨立的,因此在不同伺服器的程序間會存在快取不一致的情況。即使EhCache提供了叢集環境下的快取同步策略,但是同步依然是需要一定的時間,短暫的快取不一致依然存在。 在一些要求高一致性(任何資料變化都能及時的被查詢到)的系統和應用中,就不能再使用EhCache來解決了,這個時候使用集中式快取就可以很好的解決快取資料的一致性問題。接下來我們就來學習一下,如何在Spring Boot的快取支援中使用Redis實現資料快取。 ## 動手試試 本篇的實現將基於[上一篇](http://blog.didispace.com/spring-boot-learning-21-5-3/)的基礎工程來進行。先來回顧下上一篇中的程式要素: **User實體的定義** ```java @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實體的資料訪問實現(涵蓋了快取註解)** ```java @CacheConfig(cacheNames = "users") public interface UserRepository extends JpaRe