SpringBoot supports caching components in SpringBoot, Data storage is dependent on the Spring framework cache cache management related org. Springframework. Cache. The cache and org., springframework. Cache. CacheManager cache manager interface.

If a Bean component of type CacheManager or a CacheResolver cache parser named CacheResolver is not defined in the program, SpringBoot will attempt to select the following cache components (in the specified order) to be enabled:

(1) Generic

(2) JCache (JSR-107) (Ehcache 3, Hazelcast, Infinispan, etc)

(3) Ehcache 2.x

(4) Hazelcast

(5) Infinispan

(6) Couchbase

(7) Redis

Caffeine (8)

Simple (9)

The above list lists the nine cache components supported by SpringBoot in the order in which they are loaded. 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 a project at the same time, and no CacheManager or cacheResolver (CacheManager or CacheSolver) is specified, SpringBoot will enable the first cache component for cache management in the order described above (for example, If both the Couchbase and Redis cache components are added, the Couchbase component is enabled first).

In the previous article, SpringBoot Cache Management (1) introduced the default cache management, we built a project without adding any cache management components, but we still implemented cache management. This is because when cache management is enabled, SpringBoot will look for valid cache components in the order described above for cache management. If there are no cache components, it will default to the last Simple cache component for management. The Simple cache component is the default cache management component for SpringBoot. By default, it uses an in-memory ConcurrentMap for cache storage, so it is possible to implement in-memory cache management without adding any third-party cache components, but it is not recommended.

Redis cache component is introduced on the basis of SpringBoot cache management (I) default cache management project, and the specific implementation of integrating Redis cache with SpringBoot is explained in the way of annotation.

(1) Add Spring Data Redis Dependence Launcher

Add the Spring Data Redis Dependency Launcher to the Pom.xml file:


org.springframework.boot

spring-boot-starter-data-redis
When we add the Redis-related dependency launcher, SpringBoot will use Rediscacheconfigratioin as the auto-configuration class for the cache related auto-assembly class (previously the default SimpleCacheconfiguration), The Cache manager used in the container is changed to RedisCacheManager (previously default isCacheManager). This Cache manager creates a “RedisCache” and then controls Redis to Cache the data.

(2) Redis server connection configuration

Add the connection configuration for the Redis database in the global configuration file Application.properties for 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 blank)

spring.redis.password=

(3) Modify the methods in the CommentService class

Use @Cacheable, @CachePut and @CacheEvict to manage the cache, and store, update and delete the cache 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

    */

@Service

public class CommentService {

@Autowired private CommentRepository commentRepository; /** * @Cacheable: String springBoot (); /** * @Cacheable: String springBoot (); Set up a cache namespace, * @Param id * @Return */ @Cacheable(CacheNames = "comment", unless = "#result==null") public Comment findCommentById(Integer id){ Optional<Comment> comment = commentRepository.findById(id); if(comment.isPresent()){ Comment comment1 = comment.get(); return comment1; } return null; } /** * update comment * @param comment * @return */ @cacheput (cacheNames = "comment",key = "#result.id") public comment updateComment(Comment comment) { commentRepository.updateComment(comment.getAuthor(), comment.getaId()); return comment; } /** * deleteComment * @comment_id */ @cacheevict (cacheNames = "comment") public void deleteComment(int comment_id) { commentRepository.deleteById(comment_id); }

}

In the above code, annotation @cacheable, @cacheput and @cacheevict are used for cache management on data query, data update and data delete methods.

The key value is not marked in the query cache @cacheable annotation. The default parameter comment_id will be used as the key to save the data. The same key must be used for cache updates. Similarly, in the @cacheable annotation for using query caching, unless= “#result==null” is defined to mean that the query will not be cached if the result is null.

(4) Add two interfaces to the CommentController class

New, updated and deleted interfaces:

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

    */

@RestController

public class CommentController {

@Autowired
private 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) Annotation-based Redis query cache test

Enter in your browser: http://localhost:8080/findCommentById? Id =1;

The page reported an error, check the console information:

According to the error information: SQL statement is executed when query user Comment information COMMENT, but IllegalArgumentException is an illegal parameter when cache storage occurs. The message requires the corresponding Comment entity class to implement serialization (DefaultSerializer requires a Serializable payload but received an object of type Ment [com.hardy.springbootdatacache.entity.Com]).

(6) Serialize the cache object

(7) Restart the project test query cache

Enter in your browser: http://localhost:8080/findCommentById? If id=1 and id=1 and id=1:

Open the Redis Desktop Manager, connect to the locally enabled Redis service, and see the specific data caching effect:

The user Comment retrieved by executing the findById() method is correctly stored in the namespace named Comment in the Redis cache library.

The unique identifier of the cached data is the key value in the string “comment::+ parameter value (comment::1)”, while the value value is stored in HEX format formatted by the JDK default sequence. The data formatted after the JDK default sequence is obviously not convenient for visual viewing and management of the cached data, so in the real world development, it is common to customize the serialization format of the data, which will be covered later.

(8) Annotation-based Redis cache update test

Through the browser to access first: http://localhost:8080/updateComment? Id = 1 & author = hardy;

Then visit: http://localhost:8080/findCommentById? Id =1, view the browser return information and console print information:

As you can see, an updated SQL statement was executed when the updateComment() was executed to update the data with id 1, and no SQL statement was executed again when the findById() method was called to query the user comment information with id 1, and the browser returned the correct result after the update. This indicates that the @Cacheput cache update was successfully configured.

(9) Annotation-based Redis cache deletion test

Through the browser visit: http://localhost:8080/deleteComment? Id = 1 and http://localhost:8080/findCommentById? id=1

DeleteComment () method deletes data with id 1 and the result of the query is null.

You can see that the previously stored COMMENT data has been deleted, indicating that the @CacheEvict annotation cache deletion was successful.

As the above example shows, annotation-based Redis caching can be implemented by simply adding Redis dependencies and using several annotations on the corresponding methods.

Alternatively, Redis validity can be configured in the SpringBoot global configuration file, as shown in the following example code:

Set the validity of annotation-based Redis cache data uniformly to 1 minute in milliseconds

Spring.cache.redis.time-to-live =60000 The spring.cache.redis.time-to-live attribute is added to the SpringBoot global configuration file to set the expiration date (in milliseconds) of the Redis data, but this is not flexible enough, so it is generally not used.

In SpringBoot’s integrated Redis cache implementation, in addition to the annotation-based Redis cache implementation, there is another approach that is more commonly used in development — the API-based Redis cache implementation. This API-based Redis cache implementation needs to implement data cache management by calling related methods through the API provided by Redis under certain business requirements. At the same time, this method can also manually manage the validity of the cache.

In the following section, SpringBoot can integrate Redis cache by means of Redis API.

(1) Use Redis API for business data cache management

In com. Hardy. Springbootdatacache. Service package under a new ApiCommentService:

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

    */

@Service

public class ApiCommentService {

@Autowired private CommentRepository commentRepository; @Autowired private RedisTemplate redisTemplate; /** * @commentById * @return */ public Comment findCommentById(Integer id){/** * @commentById (String id) redisTemplate.opsForValue().get("comment_" + id); if (o ! = null) { return (Comment) o; } else {/ / if not in the cache, from a database query Optional < Comment > dbComment = commentRepository. FindById (id); if (dbComment.isPresent()) { Comment redisComment = dbComment.get(); / / the query results stored in the cache, and set up is valid for 1 day redisTemplate. OpsForValue (). The set (" comment_ "+ id, redisComment, 1, TimeUnit. DAYS); return redisComment; } else { return null; }}} /** * UpdateComment * @Param * @Return */ public comment UpdateComment { commentRepository.updateComment(comment.getAuthor(), comment.getId()); / / update the database after data cache update redisTemplate. OpsForValue (). The set (" comment_ "+ comment. GetId (), the comment). return comment; } /** * deleteComment * @comment_id */ public void deleteComment(int comment_id) { commentRepository.deleteById(comment_id); Redistemplate. delete("comment_" + comment_id); // delete redistemplate. delete("comment_" + comment_id); }

} (2) Write the 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 {

@Autowired
private 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 API based Redis cache implementation

Input: http://localhost:8080/api/findCommentById? Id = 2 (continuous input three times), http://localhost:8080/api/updateComment? Id = 2 & author = hardy, http://localhost:8080/deleteComment? Id =2;

View console messages and Redis database:

The configuration of the API-based Redis cache implementation: The API-based Redis cache implementation does not require the @Enablecaching annotation to enable annotation-based caching support, so you have the option to remove or annotate the @Enablecaching annotation that you added to the project startup class without affecting the functional implementation of the project.

If you think the article is helpful to you, you can support thumb up comments forward ~ crab crab!

The original link: https://www.tuicool.com/artic…