能夠下載案例Chapter4-4-1,進行下面改造步驟。html
先來回顧一下在此案例中,咱們作了什麼內容:git
spring-data-jpa
和EhCache
User
實體,包含id
、name
、age
字段spring-data-jpa
實現了對User
對象的數據訪問接口UserRepository
Cache
相關注解配置了緩存刪除EhCache的配置文件src/main/resources/ehcache.xml
redis
pom.xml
中刪除EhCache的依賴,增長redis的依賴:spring
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency>
application.properties
中增長redis配置,以本地運行爲例,好比: spring.redis.host=localhost spring.redis.port=6379 spring.redis.pool.max-idle=8 spring.redis.pool.min-idle=0 spring.redis.pool.max-active=8 spring.redis.pool.max-wait=-1
咱們須要作的配置到這裏就已經完成了,Spring Boot會在偵測到存在Redis的依賴而且Redis的配置是可用的狀況下,使用RedisCacheManager
初始化CacheManager
。緩存
爲此,咱們能夠單步運行咱們的單元測試,能夠觀察到此時CacheManager
的實例是org.springframework.data.redis.cache.RedisCacheManager
,並得到下面的執行結果:app
Hibernate: insert into user (age, name) values (?, ?) 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 Hibernate: select user0_.id as id1_0_0_, user0_.age as age2_0_0_, user0_.name as name3_0_0_ from user user0_ where user0_.id=? Hibernate: update user set age=?, name=? where id=? 第三次查詢:10
能夠觀察到,在第一次查詢的時候,執行了select語句;第二次查詢沒有執行select語句,說明是從緩存中得到告終果;而第三次查詢,咱們得到了一個錯誤的結果,根據咱們的測試邏輯,在查詢以前咱們已經將age更新爲20,可是咱們從緩存中獲取到的age仍是爲10。spring-boot
源碼來源單元測試