您的位置:首页 > 数据库 > Redis

Spring Cloud Spring Boot mybatis分布式微服务云架构(三十五)使用Redis做集中式缓存(1)

2018-03-08 09:31 1386 查看

准备工作

可以下载案例Chapter4-4-1,进行下面改造步骤。

先来回顾一下在此案例中,我们做了什么内容:

引入了
spring-data-jpa
EhCache


定义了
User
实体,包含
id
name
age
字段

使用
spring-data-jpa
实现了对
User
对象的数据访问接口
UserRepository


使用
Cache
相关注解配置了缓存

单元测试,通过连续的查询和更新数据后的查询来验证缓存是否生效

开始改造

删除EhCache的配置文件
src/main/resources/ehcache.xml


pom.xml
中删除EhCache的依赖,增加redis的依赖:
<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
,并获得下面的执行结果:
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。


源码来源
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐