Introduction and use of spring cache

1. Introduction

Spring has defined org.springframework.cache.Cache and org.springframework.cache.CacheManager interfaces since 3.1 to unify different caching technologies;

It also supports the use of JCache (JSR-107) annotations to simplify our development

 

The Cache interface is defined by the component specification of the Cache, including various operation sets of the Cache; Spring provides various Xcache implementations under the Cache interface; Such as RedisCache,

Ehcachecache, concurrentmapcache, etc;

 

Each time a method requiring caching is called, Spring will check whether the specified target method of the specified parameter has been called; If so, get the method directly from the cache

If there is no result after the call, call the method and cache the result and return it to the user. Get directly from cache for next call

 

2. Integrate spring cache to simplify cache development

1) Introduce dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

 

2) Add configuration

spring.cache.type=redis

 

3) Test using cache

@Cacheable   Triggers the operation of saving data to the cache
@CacheEvict  Delete data from cache
@CachePut    Does not affect method execution update cache
@Caching     Combine the above operations
@CacheConfig At the class level, share the same configuration as the cache

 

① Add @ EnableCache annotation on the main startup class to enable the cache function

 

② . you can complete the cache operation only by using annotations

When the results of the method need to be cached in the database, add @ CacheEnable annotation on the method

/*
1,For each data that needs to be cached, we need to specify which name to put in the cache. [equivalent to cache partition (partition according to business type)]
2,The result representing the current method needs to be cached. If there is in the cache, the method will not be called; If there is no in the cache, the method is called and the result returned by the method is put into the cache
3,Default behavior
    1)The method cannot be called if it is in the cache
    2)key The value is generated by default, and the name of the cache:: simplekey []
    3)The cached value uses the jdk serialization mechanism by default to store the serialized data in redis
    4)The default cache expiration time is - 1 (user expiration)

    Custom:
    1)Specify the key generated by the cache: specify the key - > spel expression
    2)Specify the expiration time of cached data: specified by the configuration file
    3)Save data in json format:

*/
@Cacheable("category")
@Override
public List<CategoryEntity> getLevel1Categorys() {
    System.out.println("getLevel1Categorys Method execution......");
    List<CategoryEntity> categoryEntities = this.baseMapper
        .selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", "0"));
    return categoryEntities;
}

When accessing this method for the first time, you need to access the database; The second time the method is accessed, it is retrieved directly from the cache

 

③ . set the name and expiration time of the key in a user-defined way

@Cacheable(value = {"category"},key="'level1Categorys'")

 

Add to profile

#In Milliseconds 
spring.cache.redis.time-to-live=3600000

 

④ . more custom configurations

Configure the serialization mechanism of key and value:

/**
 * @author houChen
 * @date 2021/11/4 6:59
 * @Description:
 *
 * Cache configuration class
 *    @ConfigurationProperties(prefix = "spring.cache") :  It just binds the properties in the class to the configuration file, and cannot be injected into the container
 *
 */
@EnableConfigurationProperties(CacheProperties.class)    //@The EnableConfigurationProperties annotation enables the CacheProperties class to be injected into the container
@Configuration
@EnableCaching
public class MyCacheConfig {

    @Bean
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        config=config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config=config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        CacheProperties.Redis redisCacheProperties = cacheProperties.getRedis();
        if(redisCacheProperties.getTimeToLive()!=null){
            config = config.entryTtl(redisCacheProperties.getTimeToLive());
        }
        return config;
    }
}

 

⑤ Use @ CacheEvict (remove cache)

Specifies to delete all data under a partition

@CacheEvict(value="category",allEntries=true)

appointment:

Data of the same type can be cached in partitions with the same name!

 

3. Principles and shortcomings of SpringCache

1) Read mode

Cache penetration: query a null data. Solution: cache null values = true

Cache breakdown: a large number of concurrent requests come in and query an expired data at the same time. Solution: lock

Cache avalanche: a large number of Keys expire at the same time. Solution: add random time

 

2) Write mode (how to ensure cache and database consistency)

1) Lock mode

2) Introducing canal

 

3) Read more and write more. Go directly to the database for query

Tags: Redis

Posted on Mon, 29 Nov 2021 02:02:14 -0500 by marty