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

准备工做

能够下载案例Chapter4-4-1,进行下面改造步骤。html

先来回顾一下在此案例中,咱们作了什么内容:git

  • 引入了spring-data-jpaEhCache
  • 定义了User实体,包含idnameage字段
  • 使用spring-data-jpa实现了对User对象的数据访问接口UserRepository
  • 使用Cache相关注解配置了缓存
  • 单元测试,经过连续的查询和更新数据后的查询来验证缓存是否生效

开始改造

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

  • 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

  • 源码来源单元测试

相关文章
相关标签/搜索