day112-Cache-Learning SpringCache to read this is enough (introduction, annotation use, custom configuration and shortcomings and solutions)

1 Introduction

Earlier we talked about some concepts about read mode and write mode, as well as solutions for cache coherency

This time I talked about spring cache, which is equivalent to simplifying the previous inherent operations. It can be understood as an abstraction of the cache. It is part of the spring integrated component.

With him, it is much easier for us to use the cache. Many previous operations are often done with a comment. The official learning link is as follows

https://docs.spring.io/spring-framework/docs/5.2.13.RELEASE/spring-framework-reference/

2. Learn more

The application needs to use springcache, and the application needs to be equipped with one or more cache managers, and a cache manager has different cache components. The actual addition, deletion, and modification of the cache depends on these cache components.

These caches are distinguished by name, as shown in the figure below. For example, they are divided into employee cache, salary cache, menu cache, product cache, other caches, etc.

In fact, to understand it simply, CacheManager, as a manager, is used to define rules, such as whether the storage uses ConcurrentMap, redis, mysql, or mongodb.

Or the overall expiration time of the mixed storage, and why should the cache components be divided by different names? This is actually related to your business. For example, you can define a cache for order business and commodity business.

Then you can subdivide into this cache when adding and deleting. For example, if you want to refresh the cache of the order business, it is not always good to refresh all of it.

CacheManager Cache These two parent interfaces, you can click to see what methods are available

3. Convenience of integrating SpringCache and initial experience annotation

(1) Introduce dependencies

The first one is the dependency of springcache, and the second one is to introduce whatever you want to use as a caching scene. Here is redis

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

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

(2) Write configuration

Let's first look at what is automatically configured for us after introducing dependencies, and then we know what configuration is missing, we can manually fill in

After looking at the CacheAutoConfiguration code, I found that it will be equipped with a corresponding type of cache manager, we are redis and then create a cache space

(3) Turn on the cache function

Just add the first comment below

(4) How to use each annotation

First make a brief introduction to each annotation

4.1 @Cacheable

Add the comment to the method of querying the first-level classification that will be called when you visit the home page before

I visited and refreshed the homepage, only the first time the output statement was printed, indicating that it was saved in the cache, and the subsequent method calls are actually directly accessed caches.

If there is no actual access method in the cache, if you don’t believe me, try deleting the cache.

Open the redis client and find this cache, you can see that his key is the default, the expiration time -1 is never expired, and the value is the result of jdk serialization. We can define these by ourselves later

 4.2 Modify various default configurations

Let’s implement the previous sentence now

Various attributes in @Cacheable

The following figure shows the various attributes in Cacheable. We only set the value above. In fact, we can also set the key or key generator, what conditions are cached, what conditions are not cached, etc. Is it synchronized?

4.2.1 Set key

As follows, remember that the key is a SpEL expression, such as a string, remember to add two single quotes

http://SpEL expression link  key can be a method name or something

4.2.2 Set expiration time

This we said before, the automatic configuration class will load the application.properties configuration file

Here we set the expiration time to one hour

4.3.3 Change the value in the cache to json format to prevent compatibility issues

Here you need to customize the configuration class, I will not say much about the process, read

RedisCacheConfiguration后 得知,我们自定义配置类,并覆盖redisconfig对象,以及添加自己的配置即可
package com.atguigu.gulimall.product.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author rengang
 * @version 1.0
 * @date 2021/3/28 15:47
 */

@EnableConfigurationProperties(CacheProperties.class)
@Configuration
@EnableCaching
public class MyCacheConfig {


    @Bean
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){

        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();

        //键值 缓存类型设置  键采用string 值采用 generic json 也就是支持泛型的json
        config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));

        CacheProperties.Redis redisProperties = cacheProperties.getRedis();


        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;

    }

}

application.properties

spring.cache.type=redis

spring.cache.cache-names= music,pic

spring.cache.redis.time-to-live= 3600000

spring.cache.redis.key-prefix= Cache-

#缓存空值,默认就是true
spring.cache.redis.cache-null-values= true

Then open the redis client tool, you can see that the various configurations for the cache above are in effect

4. Shortcomings of springCache and solutions

Guess you like

Origin blog.csdn.net/JavaCoder_juejue/article/details/115107654