SoFunction
Updated on 2025-03-02

SpringBoot Integration Redis Using Cache Cache Implementation Method

Use SpringBoot to integrate Redis to use Cache cache as long as you configure the corresponding configuration class and then use Cache annotation to achieve it

RedisConfig configuration

Create a new RedisConfig configuration class

package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import .Jackson2JsonRedisSerializer;
import ;
import ;
import ;
import ;
import ;
/**
 * @author cuishujian
 * @date 2024/9/25
 */
@Configuration
@EnableCaching// Turn on cachepublic class RedisConfig extends CachingConfigurerSupport {
    /**
      * Customize the rules for generating keys
      * In the cache object collection, the cache is saved in the form of key-value
      * When a cached key is not specified, SpringBoot will use SimpleKeyGenerator to generate keys
      * @return
      */
    @Bean
    public KeyGenerator keyGenerator(){
        return new KeyGenerator(){
            public Object generate(Object target, Method method, Object... params){
                // Format cache key string                StringBuilder sb = new StringBuilder();
                // Append class name                (().getName());
                // Append method name                (());
                // traverse the parameters and add them                for (Object obj : params) {
                    (());
                }
                return ();
            }
        };
    }
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        (redisConnectionFactory);
        // Solve the problem of query cache conversion exception        ObjectMapper om = new ObjectMapper();
        (, );
        (.NON_FINAL);
        // Replace default serialization with Jackson2JsonRedisSerialize        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(om, );
        // Set the serialized object of value and the serialized object of key        (jackson2JsonRedisSerializer);
        (new StringRedisSerializer());
        ();
        return redisTemplate;
    }
    /**
      * Use RedisCacheManager as cache manager
      */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory){
        // Create Redis serialization object        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        // Solve the problem of query cache conversion exception        ObjectMapper om = new ObjectMapper();
        (, );
        (.NON_FINAL);
        // Create Jackson's serialized object        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(om, );
        // Configure serialization (solve garbled problems)        RedisCacheConfiguration config = ()
                // 7-day cache expires                .entryTtl((7))
                .serializeKeysWith((redisSerializer))
                .serializeValuesWith((jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = (factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

The above code is explained as follows:

@EnableCaching: Use this annotation to enable cache

keyGenerator(): Use this method to customize key generation rules

redisTemplate(): Use this method to change the default serialization rules and serialize the data into json format. When we introduced spring-boot-starter-data-reids, the RedisAutoConfiguration automatic configuration class injected two components RedisTemplate<Object, Object> and StringRedisTemplate to operate redis. The key values ​​of RedisTemplate<Object, Object> are all objects, and StringRedisTemplate is used to operate strings. RedisTemplate uses JdkSerializationRedisSerializer. Saving data will serialize the data into byte data and then deposit it into Redis. If you want to serialize the data into json format, you need to change the default serialization rules.

cacheManager(): Use this method to customize RedisCacheManager to change the default serialization rules and serialize data into json format

Cache Notes

@Cacheable

  • Function: It is mainly aimed at method configuration, and can cache its results according to the request parameters of the method. During query, data will be fetched from the cache first, and access to the database will be initiated if it does not exist.
  • parameter:
    • value/cacheNames: Specify the collection name of the cache storage.
    • key: The key value stored in the Map collection of cache objects is not required. By default, all parameters of the function are combined as key values. If you configure it yourself, you need to use SpEL expressions.
    • condition: The conditions for cache objects are not required, and SpEL expressions are also required. Only contents that meet the expression conditions will be cached.
    • unless: Another cache conditional parameter, which is not required, also requires the use of SpEL expression, but the timing is determined after the function is called, so it can be judged by the result.
    • keyGenerator: Used to specify the key generator, not required.
    • cacheManager: Used to specify which cache manager to use, not required.
    • cacheResolver: Used to specify which cache parser to use, not required.
  • Example:@Cacheable(value = "user", key = "#id"), means to use id as key to cache the return result of the method into a cache named "user".

@CachePut

  • Function: It mainly focuses on method configuration, can cache its results according to the request parameters of the method, and triggers the call of the real method every time (unlike @Cacheable). Mainly used for data addition and modification operations.
  • Parameters: Similar to @Cacheable.
  • Example:@CachePut(value = "user", key = "#"), as a key, update the return result of the method to a cache named "user".

@CacheEvict

  • Function: It mainly focuses on method configuration, and can clear the cache according to certain conditions. Usually used in deletion methods.
  • parameter:
    • value/cacheNames: Specify the collection name of the cache storage.
    • key: Specifies the key value of the clear data.
    • allEntries: Non-essential, default is false. If set to true, all data under the cache component is cleared.
    • beforeInvocation: Non-essential, default is false. If set to true, the cache is cleared before the method is executed, otherwise it is cleared after the method is executed.
  • Example:@CacheEvict(value = "user", key = "#id"), indicates the number of key id removed from the cache named "user"

This is the end of this article about SpringBoot integrating Redis with Cache Cache. For more related content related to SpringBoot using Cache Cache, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!