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

准备工作

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

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

  • 引入了spring-data-jpaEhCache
  • 定义了User实体,包含idnameage字段
  • 使用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。

  • 源码来源

猜你喜欢

转载自my.oschina.net/u/3776687/blog/1631404