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-jpa
andEhCache
- Entity is defined
User
, containingid
,name
,age
fields - Use the data access interface that
spring-data-jpa
implements the objectUser
UserRepository
- Cache is configured with
Cache
relevant 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 file
src/main/resources/ehcache.xml
-
pom.xml
Remove the dependency of EhCache and increase the dependency of redis:<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency>
application.properties
Add 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
RedisCacheManager
initialization when it detects that there is a Redis dependency and the Redis configuration is availableCacheManager
.To do this, we can step through our unit test, observe
CacheManager
the instance at this pointorg.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.