Spring cache cache notes

Spring is an abstraction layer for caching

1. Introduce dependency

spring-boot-starter-cache

spring-boot-starter-data-redis

2. Write configuration

Configure the cache used in the application

spring.cache.type=redis

2.1 cache name

It can be generated automatically without configuration,

If configured, the function of creating this name in real time will be disabled,

Only your configured name will be used in the future

3. Test using cache

//Triggers the operation of saving data to the cache
@Cacheable: Triggers cache population.
    
//Trigger the operation of deleting data from the cache -- redis failure mode for cache update
@CacheEvict: Triggers cache eviction.
    
//Does not affect method execution update cache -- redis double write mode for cache update
@CachePut: Updates the cache without interfering with the method execution.
    
//Combine the above operations
@Caching: Regroups multiple cache operations to be applied on a method.
    
//Share the same configuration of the cache at the class level
@CacheConfig: Shares some common cache-related settings at class-level.

3.1 using cache

  1. Enable cache function

    The @ EnableCaching annotation is used on the main startup class

  2. Only annotations are needed to manipulate the cache – the default setting

    • @Cacheable / / indicates that the current result needs to be cached on the location method

      If there is a method in the cache, it will not be called. If not, it will call the method and put the result of the method into the cache

    • For each data that needs to be cached, we specify which name to put in the cache

      @Cacheable(value="item")

3.2 default behavior

  1. If there is in the cache, the method is not called
  2. Keys in redis are automatically generated by default
  3. The value in the redis cache uses the jdk serialization mechanism by default to store the serialized data in redis
  4. Default ttl time - 1 never expires

3.3 * custom behavior

  1. Specify the key required to generate the cache. Use the annotated key attribute to receive a spiel. Therefore, the name of the key cannot be used directly. It needs to be enclosed in single quotes
//Specify the cache partition and the key name of the cache
@Cacheable(value="item",key="'selectItem'")
@GetMapping("/getItem")
public R selectItem(){
    
}
nameplacedescribeexample
methodNamerootThe name of the called method#root.methodName
methodrootCalled method#root.method.name
targetrootCalled target object#root.target
targetClassrootThe class of the called target#root.targetClass
argsrootParameters used to call the target (as an array)#root.args[0]
cachesrootCache collection that runs the current method#root.caches[0].name
Parameter nameEvaluation backgroundThe name of any method parameter. If the name is not available (possibly because there is no debugging information), the parameter name can also be under #a < #arg > where representing the parameter index #arg (starting from 0).#ibanor #a0 (you can also use the #p0or#p < #arg > symbol as an alias).
resultEvaluation backgroundThe result of the method call (the value to cache). Available only in an empty expression, a cache put expression (used to evaluate the key), or a cache evict expression (when beforeInvocation is false). For supported wrappers (such as Optional), #result refers to the actual object, not the wrapper.#result
  1. Specifies the lifetime of the data in the cache

Set the expiration time in the application configuration file

//In milliseconds -- 10000 milliseconds is 10 seconds
spring.cache.redis.time-to-live=10000
  1. Specify that the value of data in redis is in json format

CacheAutoConfiguration is the automatic configuration class of the cache,

Automatic configuration will import the RedisCacheConfiguration class of redis,

Redis cache configuration class will automatically configure redis cache manager RedisCacheManager

Initialize all caches

What configuration does each cache think to use? If RedisCacheConfiguration is available, use your own

If you want to change the cache configuration, you need to put a RedisCacheConfiguration for the container summary

@EnableCaching
@Configuration
public class MyRedisCacheConfig {

    @Bean
    RedisCacheConfiguration redisCacheConfiguration(){
        //Use the default configuration before we modify it
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        //Sets the cache expiration time in minutes
        config.entryTtl(Duration.ofMinutes(10));
        //Use a serialized key name of String type
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        //Using a serialized value of json type, Generic represents how it can be converted to an object
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
        return config;
    }
}

Delete cache - update cache - failure mode

@CacheEvict(value="item",key="'selectItem'")//Cache update - failure mode
//When deleting the cache, both the cache partition and the name of the key in redis need to be specified. What was stored before is now
public R updateItem(String id){
	
}

Combined operation

If updating the cache requires deleting two cache contents, one in the background of a page, you need to use the @ Caching combination operation to delete two caches

  @Caching(evict = {
            //Delete two caches
            @CacheEvict(value = "item",key = "'cacheItem'"),
            @CacheEvict(value = "item",key = "'getCacheItem'"),
    })
//perhaps
//Delete all data in the item partition
//The same type of data can be stored in the same partition. When we modify this type of data, we can directly delete all data of this type
//In the future, instead of specifying a prefix, we use its partition name as the prefix -- it is not written by default
@CacheEvict(value = "item",allEntries = true)

Cache avalanche, there is no need to set a random expiration time here,

Because the time when you join the cache is inconsistent, your expiration time is different

Spring cache solves cache problems

Write mode - ensure that the cache is consistent with the database

  1. Read / write lock
  2. The middleware Canal is introduced to sense the update of mysql and update the cache
  3. Read more and write more. Go directly to the database without caching

Read mode

  1. Cache penetration: query a null data, solve: cache null value, cache solution, configuration file configuration

     cache:
        redis:
          cache-null-values: true  # Cache null
    
  2. Cache breakdown: query a large number of values that will expire. Solution: lock access to the database,

    //cacheable annotations can use local locks. Generally speaking, local locks are enough
    @Cacheable(value="item",key="'selectItem'",sync=true)
    
  3. Cache avalanche: a large number of cache failures. Solution: add the random expiration time. You only need to add the expiration time in the cache. If you add different cache times, your expiration time will be different

summary

  1. General data: Spring cache can be used directly
  2. Special data: special design, self writing, how to store in cache, how to fail, how to ensure data consistency, distributed lock,

Keywords: Java Redis Cache

Added by LightningSt on Fri, 17 Sep 2021 17:20:45 +0300