SoFunction
Updated on 2025-04-11

SpringBoot integrates Redis with annotations for caching

Hello, friends, recently we need to cache some commonly used data in the project. There is no doubt that we have used Redis to cache data. Then useWhat are the ways to cache data in RedisWoolen cloth? Next I will come one by one.

1. Environment construction

Introducing Redis dependencies and Spring-related dependencies

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

2. Use RedisTemplate

When calling the API using RedisTemplate, we usually need to configure the key and value serializer, and create a RedisUtils class to complete the cache addition, deletion, modification and query and expiration time setting.

The configuration is as follows:

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate&lt;String, Object&gt; redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate&lt;String, Object&gt; template = new RedisTemplate&lt;&gt;();
        (factory);

        // Set the serialization method of key        (());
        // Set the serialization method of value        (());
        // Set the serialization method of hash key        (());
        // Set the serialization method of hash value        (());

        ();
        return template;
    }
}

RedisUtils:

public class RedisUtils {

    @Resource
    private RedisTemplate&lt;String, Object&gt; redisTemplate;

    public Object get(String key) {
        return key == null ? null : ().get(key);
    }

    /**
      * Normal cache is stored
      *
      * @param key
      * @param value
      */

    public void set(String key, Object value) {
        ().set(key, value);
    }

    /**
      * Normal cache is placed and set time
      *
      * @param key
      * @param value
      * @param time Time (seconds) time must be greater than 0 If time is less than or equal to 0, an indefinite period will be set
      */

    public void set(String key, Object value, long time) {
        if (time &gt; 0) {
            ().set(key, value, time, );
        } else {
            set(key, value);
        }
    }

    /**
      * Put data into a hash table, if it does not exist, it will be created
      *
      * @param key
      * @param item
      * @param value
      */
    public void hset(String key, String item, Object value) {
        ().put(key, item, value);
    }

    /**
      * Put data into a hash table, if it does not exist, it will be created
      *
      * @param key
      * @param item
      * @param value
      * @param time time (seconds) Note: If the existing hash table has time, the original time will be replaced here.
      */
    public void hset(String key, String item, Object value, long time, TimeUnit timeUnit) {
        ().put(key, item, value);
        if (time &gt; 0) {
            expire(key, time, timeUnit);
        }
    }

    /**
      * @param key
      * @param map multiple fields-values
      */
    public void hmset(String key, Map&lt;String, Object&gt; map) {
        ().putAll(key, map);
    }

    /**
      * @param key
      * @param map multiple fields-values
      * @param time Expiry time
      * @param timeUnit TimeUnit
      */
    public void hmset(String key, Map&lt;String, Object&gt; map, long time, TimeUnit timeUnit) {
        ().putAll(key, map);
        if (time &gt; 0) {
            expire(key, time, timeUnit);
        }
    }

    /**
      * @param key
      * @param item Field
      * @return The obtained value
      */
    public Object hget(String key, String item) {
        return ().get(key, item);
    }

    /**
      * @param key
      * @return map corresponding to the key in the hash table
      */
    public Map&lt;Object, Object&gt; hEntries(String key) {
        return ().entries(key);
    }

    /**
      * @param key
      * @param value
      */
    public void sadd(String key, Object value) {
        ().add(key, value);
    }

    /**
      * @param key
      * @param value
      * @param time Expiry time
      * @param timeUnit TimeUnit
      */
    public void sadd(String key, Object value, long time, TimeUnit timeUnit) {
        ().add(key, value);
        if (time &gt; 0) {
            expire(key, time, timeUnit);
        }
    }

    /**
      * @param key
      * @return data
      */
    public Set&lt;Object&gt; smembers(String key) {
        return ().members(key);

    }

    public void expire(String key, long time, TimeUnit timeUnit) {
        if (time &gt; 0) {
            (key, time, timeUnit);
        }
    }

    /**
      * Get expiration time according to key
      *
      * @param key key cannot be null
      * @return Time (seconds) Return 0 means permanently valid
      */
    public long getExpire(String key) {
        return (key, );
    }
}

Through the above configuration, when we use cache, we can directly call the API to operate. But there is a problem that when we cache some commonly used data, we usually need to first determine whether there is the key in the cache. If not, we will query it in the database and cache it.

In this way, we need to do some judgment operations. If there is one in the cache, go to the cache and fetch it. If there is no one, take it out of the database and cache it. So is there a more convenient way to operate? Of course there are answers.

3. Use @EnableCaching+@Cacheable

Spring provides us with a Caching module, which can provide us with the functions provided by this module, and it is very convenient to complete data caching using annotations.

During the use, I found that although we configured itRedisTemplateSerialization, but is invalid for the annotation-based Redis cache, we need to configure a custom oneRedisCacheManager

The configuration is as follows:

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate&lt;String, Object&gt; redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate&lt;String, Object&gt; template = new RedisTemplate&lt;&gt;();
        (factory);

        // Set the serialization method of key        (());
        // Set the serialization method of value        (());
        // Set the serialization method of hash key        (());
        // Set the serialization method of hash value        (());

        ();
        return template;
    }

    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory factory) {
        RedisCacheWriter redisCacheWriter = (factory);
        RedisCacheConfiguration redisCacheConfiguration = ()
            .serializeKeysWith((()))
            .serializeValuesWith((()));
        return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
    }
}

How to use:

  1. Add on the startup class@EnableCaching
  2. Add to the method that needs to cache data@Cacheable(cacheNames = "xxx"), the return value of the method is the data we need to cache
  3. Based on the above operations, we can easily cache the data that needs to be cached to Redis

Summarize

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