SoFunction
Updated on 2025-03-03

How to enable cache @EnableCaching (using redis)

Add dependencies

<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Configure the redis connection parameters

spring:
  # redis configuration  redis:
    # address    host: 127.0.0.1
    # port, default is 6379    port: 6379
    # Database Index    database: 2
    # password    password:
    # Connection timeout    timeout: 10s

Configuration class

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import .Jackson2JsonRedisSerializer;
import ;

import ;
import ;
import ;


@Configuration
public class CacheConfig {

    /**
      * Latest version, set the expiration time of redis cache
      */
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        return new RedisCacheManager(
                (redisConnectionFactory),
                ( 60) // Default policy, unconfigured key will use this        );
    }

    private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
        Jackson2JsonRedisSerializer&lt;Object&gt; jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer&lt;&gt;();
        ObjectMapper om = new ObjectMapper();
        (, );
        (.NON_FINAL);
        (om);
        RedisCacheConfiguration redisCacheConfiguration = ();
        redisCacheConfiguration = (
                RedisSerializationContext
                        .SerializationPair
                        .fromSerializer(jackson2JsonRedisSerializer)
        ).entryTtl((seconds));
        return redisCacheConfiguration;
    }

}

Add @EnableCaching annotation to the startup class

test

1. Interface query

2. Cache query verification

@ApiOperation(value = "Get details based on ID",notes = "Query")
@Cacheable(cacheNames = "testaCache", key = "#id")
@RequestMapping(value = "/get/{id}",method = )
public TestA get(@PathVariable Long id){
    ("Mysql query was performed");
    return (id);
}
 @GetMapping("/get/redis/cache")
 @ApiOperation(value="View Redis Cache Information")
 public String getRedisCache(){
 	// Get beans by type from IOC container     RedisCacheManager redisCacheManager = ();
     // Get bean by name from IOC container     RedisCacheManager redisCacheManager2 = ("cacheManager");
     Cache demoCache = ("testaCache");
     ((78, )+"");
     return ();
 }

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

@Component
public final class SpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware 
{
    /** Spring application context environment */
    private static ConfigurableListableBeanFactory beanFactory;

    private static ApplicationContext applicationContext;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException 
    {
         = beanFactory;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException 
    {
         = applicationContext;
    }

    /**
      * Get the object
      *
      * @param name
      * @return Object An instance of a bean registered with the given name
      * @throws BeansException
      *
      */
    @SuppressWarnings("unchecked")
    public static &lt;T&gt; T getBean(String name) throws BeansException
    {
        return (T) (name);
    }

    /**
      * Get an object of type requiredType
      *
      * @param clz
      * @return
      * @throws BeansException
      *
      */
    public static &lt;T&gt; T getBean(Class&lt;T&gt; clz) throws BeansException
    {
        T result = (T) (clz);
        return result;
    }

    /**
      * Return true if the BeanFactory contains a bean definition that matches the given name
      *
      * @param name
      * @return boolean
      */
    public static boolean containsBean(String name)
    {
        return (name);
    }

    /**
      * Determine whether the bean definition registered with a given name is a singleton or a prototype.  If the bean definition corresponding to the given name is not found, an exception will be thrown (NoSuchBeanDefinitionException)
      *
      * @param name
      * @return boolean
      * @throws NoSuchBeanDefinitionException
      *
      */
    public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException
    {
        return (name);
    }

    /**
      * @param name
      * @return Class The type of registered object
      * @throws NoSuchBeanDefinitionException
      *
      */
    public static Class&lt;?&gt; getType(String name) throws NoSuchBeanDefinitionException
    {
        return (name);
    }

    /**
      * If the given bean name has alias in the bean definition, these aliases are returned.
      *
      * @param name
      * @return
      * @throws NoSuchBeanDefinitionException
      *
      */
    public static String[] getAliases(String name) throws NoSuchBeanDefinitionException
    {
        return (name);
    }

    /**
      * Get the aop proxy object
      *
      * @param invoker
      * @return
      */
    @SuppressWarnings("unchecked")
    public static &lt;T&gt; T getAopProxy(T invoker)
    {
        return (T) ();
    }

    /**
      * Get the current environment configuration, return null without configuration
      *
      * @return Current environment configuration
      */
    public static String[] getActiveProfiles()
    {
        return ().getActiveProfiles();
    }

    /**
      * Get the value in the configuration file
      *
      * @param key configuration file key
      * @return The value of the current configuration file
      *
      */
    public static String getRequiredProperty(String key)
    {
        return ().getRequiredProperty(key);
    }
}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.