spring cache Basics

Keywords: Java Spring Boot

Spring has defined org.springframework.cache.Cache and   org.springframework.cache.CacheManager interface to unify different caching technologies; And support the use of   JSR-107   Annotations simplify our development;

Provides implementations that support multiple caches.

There are two main interfaces:

  1. org.springframework.cache.Cache: used to define various cache operations
  2. org.springframework.cache.CacheManager  : Used to manage various cache components

Common notes:

 @ Cacheable     It is usually used to configure a method and inject the returned result of the method into the cache object (save cache)

                If there is in the cache, the method will not be called. If there is no cache, the method will be called and the result will be put into the cache

@CacheEvict    Can be used for classes or methods to empty the cache (delete the cache)     (use this note for failure modes)

@CachePut :    

      Enforce the method and put the returned result into the cache instead of like  @ Cacheable   In that way, first look for whether there is a cache for the returned result of the method from the cache (it does not affect the method execution to update the cache)     (this annotation is used in double write mode)

@Caching     Combine the above operations

@CacheConfig     It is used to configure the class and the cache of the whole class. It is available  @ Cacheable replacement

@EnableCaching    The startup class for SpringBoot enables the annotation function


    <groupId>org.springframework.b oot</groupId>
  	#The specified cache type is redis
    type: redis
      # Specify the expiration time in redis as 1h
      time-to-live: 3600000

Default behavior:

   > If there is in the cache, the method will not be called

   > key: automatically generated by default: cache name: SimpleKey

   > The cached value uses the jdk serialization mechanism by default to save the serialized data to redis

   > Default ttl time: - 1, i.e. never expires


   > Specifies the key of the generated cache     Use the attribute key in the annotation to specify the key = "'xxx '" which needs to be enclosed in single quotation marks,

            Otherwise, it will be considered as an expression, and a value is the partition for configuring the key (in spring, redis does not)

   > The cached value is saved in json format

   > Set the expiration time of the key   : It has been configured in the above configuration file

Configure json format of value

public class MyCacheConfig {

    //Method parameters will be passed in through injection. Of course, we can also use variables to inject
    public RedisCacheConfiguration redisCacheConfiguration( CacheProperties cacheProperties) {
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration
        //Specifies that the cache serialization method is json
        config = config.serializeValuesWith(
            RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        //The following four configurations cannot be read if we do not write them here. The default configuration will also be available, but we need to add them if we write the configuration class ourselves,

        //Set various configurations in the configuration file, such as expiration time
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
         //Prefix of key
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());

        //Cache null values
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();

         //Whether to use the prefix of key
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        return config;

//Note that if you configure your own class through the source code, you need to configure the configuration file here, otherwise it will not take effect, such as expiration time, prefix, etc.

Of course, with these configurations, the configuration file must be indispensable

 Add the expiration time configured above.

Another thing to note is,
We said before@Cacheable()annotation,His value Is configured key The name of the partition,
If we are in the configuration file spring.cache.redis.key-prefix The prefix configured inside will overwrite the partition configured in the annotation.
If spring.cache.redis.use-key-prefix by false If so, the configuration prefixes on both sides will not take effect, that is, there is no prefix

   The same 1 partition name is used for the same type of data to facilitate deletion and update
   No prefix is set in the configuration file, and the same annotation is used value Prefix the partition name

So how does spring cache solve cache penetration, cache breakdown and cache avalanche

Among them, cache penetration, we set the cacheable null value in the configuration file, so it is equivalent to solving the problem

In case of cache avalanche, because the expiration time of key is added in the configuration file, and because the time lines of programs are different, the unified expiration time setting can reach different expiration times of kry,

If the cache is broken down, add the attribute to the @ Cacheable(sync=true) annotation,

Internally, it is a local synchronized lock. If it is judged that there is no value, open a thread task to get the value from the database, and then set the value into the cache for return.

Write mode: write more and read more, or write more and read less. It is recommended to directly use the database instead of cache,

Or use canal

Posted by goodluck4287 on Tue, 16 Nov 2021 07:10:06 -0800