In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "SpringBoot integration Redis cache how to achieve", the content of the article is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn "SpringBoot integration Redis cache how to achieve" it!
In SpringBoot, the cache management storage of data depends on the cache-related org.springframework.cache.Cache and org.springframework.cache.CacheManager cache manager interfaces in the Spring framework.
If no Bean component of type CacheManager or a CacheResolver cache parser named cacheResolver is defined in the program, SpringBoot attempts to enable the following caching components (in the specified order):
(1) Generic
(2) JCache (JSR-107) (EhCache 3, Hazelcast, Infinispan, etc.)
(3) EhCache 2.x
(4) Hazelcast
(5) Infinispan
(6) Couchbase
(7) Redis
(8) Caffeine
(9) Simple
The nine cache components supported by SpringBoot are listed above according to the loading order of SpringBoot cache components. When a cache management component (such as Redis) is added to the project, the SpringBoot project selects and enables the corresponding cache manager. If multiple cache components are added to the project at the same time, and no cache manager or cache parser (CacheManager or cacheResolver) is specified, then SpringBoot prioritizes one of the added cache components in the above order for cache management (for example, if both Couchbase and Redis cache components are added, then the Couchbase component is preferred).
In the previous article SpringBoot cache management (1) default cache management introduced in the default cache management, we built the project did not add any cache management components, but still implemented cache management. This is because when cache management is enabled, SpringBoot will look for valid cache components in the above cache component order for cache management. If there are no cache components, the last Simple cache component will be used for cache management by default. Simple cache component is the default cache management component of SpringBoot, which uses in-memory ConcurrentMap for cache storage by default, so it can still achieve in-memory cache management without adding any third-party cache components, but this cache management method is not recommended.
Based on the project of SpringBoot cache management (I) default cache management, the Redis cache component is introduced to explain the specific implementation of SpringBoot integration of Redis cache in an annotated way.
(1) add Spring Data Redis dependent initiator
Add a Spring Data Redis dependent initiator to the pom.xml file:
Org.springframework.boot spring-boot-starter-data-redis
When we add Redis-related dependent initiators, SpringBoot will use RedisCacheConfigratioin as the auto-configuration class for cache-related auto-assembly classes (previously the default SimpleCacheConfiguration), the cache manager used in the container has become RedisCacheManager (previously the default is cacheManager), and the Cache created by this cache manager is RedisCache, which in turn manipulates Redis to cache data.
(2) Redis server connection configuration
Add the connection configuration of the Redis database to the global configuration file application.properties of the project. The sample code is as follows:
# Redis server address spring.redis.host=127.0.0.1# Redis server connection port spring.redis.port=6379# Redis server connection password (default is empty) spring.redis.password=
(3) modify the methods in the CommentService class
Use @ Cacheable, @ CachePut and @ CacheEvict annotations for cache management to perform cache storage, cache update and cache deletion operations respectively:
Package com.hardy.springbootdatacache.service;import com.hardy.springbootdatacache.entity.Comment;import com.hardy.springbootdatacache.repository.CommentRepository;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.cache.annotation.CacheEvict;import org.springframework.cache.annotation.CachePut;import org.springframework.cache.annotation.Cacheable;import org.springframework.stereotype.Service;import java.util.Optional;/** * @ Author: HardyYao * @ Date: 2021-6-19 * / @ Servicepublic class CommentService {@ Autowiredprivate CommentRepository commentRepository / * * query comments according to comment id * @ Cacheable: store the query result comment of this method in the SpringBoot default cache * cacheNames: create a cache namespace corresponding to the cache unique ID * @ param id * / @ Cacheable (cacheNames = "comment", unless = "# result==null") public Comment findCommentById (Integer id) {Optional comment = commentRepository.findById (id) If (comment.isPresent ()) {Comment comment1 = comment.get (); return comment1;} return null;} / * * Update comments * @ param comment * @ return * / @ CachePut (cacheNames = "comment", key = "# result.id") public Comment updateComment (Comment comment) {commentRepository.updateComment (comment.getAuthor (), comment.getaId ()); return comment } / * * Delete comments * @ param comment_id * / @ CacheEvict (cacheNames = "comment") public void deleteComment (int comment_id) {commentRepository.deleteById (comment_id);}}
In the above code, @ Cacheable, @ CachePut, and @ CacheEvict annotations are used to cache data queries, data updates, and data deletion methods.
There is no key value marked in the query cache @ Cacheable annotation, so the default parameter value comment_id will be used as the key to save the data. The same key; must be used for cache updates. Similarly, in the query cache @ Cacheable annotation, unless= "# result==null" is defined to indicate that the query result is empty and not cached.
(4) add two interfaces to the CommentController class
New updated and deleted APIs:
Package com.hardy.springbootdatacache.controller;import com.hardy.springbootdatacache.entity.Comment;import com.hardy.springbootdatacache.service.CommentService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * @ Author: HardyYao * @ Date: 2021-6-19 * / @ RestControllerpublic class CommentController {@ Autowiredprivate CommentService commentService @ RequestMapping (value = "/ findCommentById") public Comment findCommentById (Integer id) {Comment comment = commentService.findCommentById (id); return comment;} @ RequestMapping (value = "/ updateComment") public Comment updateComment (Comment comment) {Comment oldComment = commentService.findCommentById (comment.getId ()); oldComment.setAuthor (comment.getAuthor ()); Comment comment1 = commentService.updateComment (oldComment); return comment1 } @ RequestMapping (value = "/ deleteComment") public void deleteComment (Integer id) {commentService.deleteComment (id);}}
(5) Redis query cache test based on annotations
Enter: http://localhost:8080/findCommentById?id=1 in the browser to access:
If an error is reported on the page, check the console information:
According to the error message, the corresponding SQL statement was executed when querying the user comment information Comment, but an illegal parameter exception of IllegalArgumentException occurred during cache storage. The prompt message requires that the corresponding Comment entity class must be serialized (DefaultSerializer requires a Serializable payload but received an object of type [com.hardy.springbootdatacache.entity.Comment]).
(6) serialize the cache object
(7) restart the project test query cache
Enter: http://localhost:8080/findCommentById?id=1 in the browser for access (three consecutive visits):
Open the Redis client visualization tool Redis Desktop Manager, and connect to the locally enabled Redis service to view the specific data caching effect:
The user comment information Comment queried by the findById () method is correctly stored in the Redis cache under the namespace named comment.
The unique identifier key value of the cached data is represented by the string "namespace comment::+ parameter value (comment::1)", while the value value is stored in HEX format after the JDK default sequence format. This kind of JDK default sequence formatted data is obviously not convenient for visual viewing and management of cache data, so in actual development, we usually customize the serialization format of the data, which will be described later.
(8) Redis cache update test based on annotations
First visit through the browser: http://localhost:8080/updateComment?id=1&author=hardy
Then, after visiting: http://localhost:8080/findCommentById?id=1, check the returned information of the browser and the printing information on the console:
You can see that an updated SQL statement was executed when updateComment () was executed to update the data with id 1. When the findById () method was called to query the user comment information with id 1, the query SQL statement was not executed again, and the browser returned the correct result after the update, which indicates that the @ CachePut cache update configuration is successful.
(9) Redis cache deletion test based on annotations
Access through browsers: http://localhost:8080/deleteComment?id=1 and http://localhost:8080/findCommentById?id=1
After executing the deleteComment () method to delete the data with id 1, the query result is empty, and view the Redis cache database:
You can see that the previously stored comment-related data has been deleted, indicating that the @ CacheEvict annotation cache deletion has been successfully implemented.
As can be seen from the above case, using the annotation-based Redis cache implementation, you only need to add Redis dependencies and use a few annotations on the corresponding methods to achieve data cache management.
In addition, you can configure the Redis validity period in the SpringBoot global configuration file. The sample code is as follows:
# set the validity period for annotation-based Redis cache data to 1 minute (in millisecond spring.cache.redis.time-to-live=60000)
In the above code, the "spring.cache.redis.time-to-live" attribute is added to the SpringBoot global configuration file to uniformly set the validity period of Redis data (in milliseconds), but this approach is not flexible enough, so it is generally not used.
In the implementation of SpringBoot integrated Redis cache, in addition to the annotation-based form of Redis cache, there is a more commonly used way in development-API-based Redis cache implementation. This implementation of Redis cache based on API needs to implement data cache management through API calls provided by Redis under certain business requirements. At the same time, this method can also manually manage the validity period of the cache.
Next, we will explain the specific implementation of SpringBoot integrating Redis cache through the way of Redis API.
(1) use Redis API to manage business data cache
Create a new ApiCommentService under the com.hardy.springbootdatacache.service package:
Package com.hardy.springbootdatacache.service;import com.hardy.springbootdatacache.entity.Comment;import com.hardy.springbootdatacache.repository.CommentRepository;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.cache.annotation.CacheEvict;import org.springframework.cache.annotation.CachePut;import org.springframework.cache.annotation.Cacheable;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Service;import java.util.Optional;import java.util.concurrent.TimeUnit / * @ Author: HardyYao * @ Date: 2021-6-19 * / @ Servicepublic class ApiCommentService {@ Autowiredprivate CommentRepository commentRepository; @ Autowiredprivate RedisTemplate redisTemplate;/** * query comments based on comments id * @ param id * @ return * / public Comment findCommentById (Integer id) {/ / check Redis cache Object o = redisTemplate.opsForValue (). Get ("comment_" + id); if (o! = null) {return (Comment) o } else {/ / if not in the cache, query from the database Optional dbComment = commentRepository.findById (id); if (dbComment.isPresent ()) {Comment redisComment = dbComment.get (); / / store the query results in the cache and set the validity period to 1 day redisTemplate.opsForValue (). Set ("comment_" + id, redisComment,1, TimeUnit.DAYS); return redisComment;} else {return null } / * Update comments * @ param comment * @ return * / public Comment updateComment (Comment comment) {commentRepository.updateComment (comment.getAuthor (), comment.getId ()); / / Cache update redisTemplate.opsForValue () .set ("comment_" + comment.getId (), comment) after updating the database data; return comment } / * delete comments * @ param comment_id * / public void deleteComment (int comment_id) {commentRepository.deleteById (comment_id); / / cache delete redisTemplate.delete ("comment_" + comment_id) after deleting database data;}}
(2) write Web access layer ApiCommentController
Package com.hardy.springbootdatacache.controller;import com.hardy.springbootdatacache.entity.Comment;import com.hardy.springbootdatacache.service.ApiCommentService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * @ Author: HardyYao * @ Date: 2021-6-19 * / @ RestController@RequestMapping ("api") / / change the request path public class ApiCommentController {@ Autowiredprivate ApiCommentService apiCommentService @ RequestMapping (value = "/ findCommentById") public Comment findCommentById (Integer id) {Comment comment = apiCommentService.findCommentById (id); return comment;} @ RequestMapping (value = "/ updateComment") public Comment updateComment (Comment comment) {Comment oldComment = apiCommentService.findCommentById (comment.getId ()); oldComment.setAuthor (comment.getAuthor ()); Comment comment1 = apiCommentService.updateComment (oldComment); return comment1 } @ RequestMapping (value = "/ deleteComment") public void deleteComment (Integer id) {apiCommentService.deleteComment (id);}}
(3) Test the implementation of Redis cache based on API
Input: http://localhost:8080/api/findCommentById?id=2 (enter three times in a row), http://localhost:8080/api/updateComment?id=2&author=hardy, http://localhost:8080/deleteComment?id=2 for access:
View console messages and Redis database:
Related configuration of API-based Redis cache implementation: API-based Redis cache implementation does not need @ EnableCaching annotation to enable annotation-based cache support, so you can choose to delete or comment the @ EnableCaching annotation added to the project startup class, which will not affect the functional implementation of the project.
Thank you for reading, the above is "SpringBoot integration Redis cache how to achieve" content, after the study of this article, I believe you have a deeper understanding of SpringBoot integration Redis cache how to achieve this problem, the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.