Spring Cloud Spring Boot mybatis distributed microservice cloud architecture (35) Using Redis for centralized caching (1)

Ready to work

You can download the case Chapter 4-4-1 and carry out the following transformation steps.

Let's review what we did in this case:

  • introduced spring-data-jpaandEhCache
  • Entity is defined User, containing id, name, agefields
  • Use the data access interface that spring-data-jpaimplements the objectUserUserRepository
  • Cache is configured with Cacherelevant annotations
  • Unit tests to verify that the cache is in effect through successive queries and queries after updating the data

start remodeling

  • Delete EhCache configuration filesrc/main/resources/ehcache.xml

  • pom.xmlRemove the dependency of EhCache and increase the dependency of redis:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-redis</artifactId>
    </dependency>

     

  • application.propertiesAdd the redis configuration to , take local operation as an example, for example:
    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
    

    The configuration we need to do is completed here. Spring Boot will use RedisCacheManagerinitialization when it detects that there is a Redis dependency and the Redis configuration is available CacheManager.

    To do this, we can step through our unit test, observe CacheManagerthe instance at this point org.springframework.data.redis.cache.RedisCacheManager, and get the following execution result:

    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
    

    It can be observed that in the first query, the select statement was executed; the second query did not execute the select statement, indicating that the result was obtained from the cache; and the third query, we obtained an incorrect result, according to Our test logic, we have updated the age to 20 before the query, but the age we get from the cache is still 10.

  • source code

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325267040&siteId=291194637