能够下载案例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
源码来源单元测试