SpringBoot2.0 combat (23) the integration of integrated cache SpringDataCache Redis
related information
Common Spring Cache Cache comment
- @CacheConfig set the current caching on the class some public settings, such as caching name.
- @Cacheable acting on the method, the results show that this method can be cached, if the cache exists, the target method will not be called directly from the cache, if the cache does not exist, the method body is performed, and the results stored in the cache.
- @CacheEvice acting on the method, remove the cache entry or empty the cache.
- @CachePut acting on the method, regardless of whether there is a cache, the method body will be executed, and the results are stored in the cache.
- @Caching acting on the method, the above comments, if multiple notes need to be wrapped in @Caching
aims
Use Redis as a cache to achieve when the additions and deletions to the database, data synchronization to update the cache, the cache from the first search query.
Ready to work
Create a table
Steps
Add dependent
The introduction of Spring Boot Starter parent project
Add Dependency redis, jpa and mysql, integers dependent on the addition of the following
Configuration
Data sources, Redis, cache configuration.
- spring.cache.type configure the cache type, default simple, and the configuration to use as a cache redis middleware, should be configured to spring.cache.type attribute redis
coding
Entity Object
Because Redis initialization, the default class sequences using JdkSerializationRedisSerializer, it is necessary to implement the Serializable interface entity object.
Repository level code
Service-level code
Add notes to the cache additions and deletions to change search method
Startup class
Added to the startup class @EnableCaching comment for opening cache
Validation results
Write test cases
The UserService the cache-related notes all comments, execute test cases, the log shows the following:
Cache recovery notes, execute test cases again, the log shows the following:
It can be seen after the use of cache, according to obtain user data when the user ID, does not perform SQL.
Go to Redis view, you can see the current Redis Key for the user :: 12, where 12 is the user's ID
Source Address
Source chapter: https://gitee.com/gongm_24/spring-boot-tutorial.git
Conclusion
High-performance database system has always been a bottleneck, reasonable proper use of caching can greatly improve system performance.
However, the ensuing increase the complexity of the system, there are more issues to be addressed, such as cache coherency, cache penetration cache avalanches.