The use of Spring cache annotation @Cacheable, @CacheEvict, @CachePut

The use of Spring cache annotation @Cacheable, @CachePut, @CacheEvict,

The Spring Cache cache annotations play the role of data caching. It simplifies the steps in the basic use of the cache. When calling the method, the parameters and return results are stored in the cache as key-value pairs. The next time you request again, if Get the result directly if it exists in the cache without requesting the database again, which increases the pressure on the database. (It feels no different from redis when you first touch it, and it really doesn’t feel any difference when you use it)

Range of use : annotations can be added to the methods in controller, service, dao (I haven't tried it on other classes), and it really works. If it fails, go to Baidu, many people have the same problem

The use of redis

Put the data in the cache into redis, get the data from redis, and use it together:

1.springboot的启动类中开启缓存,@EnableCaching
2.配置redis
    spring.redis.database=0
    spring.redis.host=xxx.sss.www
    spring.redis.port=6379
    spring.redis.password=xxxxxxxx
    spring.redis.lettuce.pool.max-active=8
    spring.redis.lettuce.pool.max-wait=-1ms
    spring.redis.lettuce.pool.max-idle=5
    spring.redis.lettuce.pool.min-idle=0
    spring.redis.lettuce.shutdown-timeout=10000
3.redis配置类的生成

redis configuration class

@Configuration
public class RedisConfig extends CachingConfigurationSelector {

    /**
     * @Description RedisTemplate配置类
     * 默认使用jdk自带的序列化,存值会出现/0Xab/0xac/00 乱码前缀
     * 修改序列化器,使用阿里的FastJson2JsonRedisSerializer
     * @param connectionFactory
     * @return
     */
    @Bean(name = {"redisTemplate"})
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory connectionFactory) {
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();

        redisTemplate.setConnectionFactory(connectionFactory);
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);
        //value对象的序列化显示
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(serializer);
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(serializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean
    public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) {
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()));
        return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
    }

}

@Cacheable annotation

The method with this annotation will store the parameters and returned results as key-value in the cache when the cache is not found. The next time the same request exists in the cache, the cache will be used directly instead of the database query;

Parameters: (I will show the parameters that are available at home here, and it is not difficult to find others by myself)

parameter nameeffect
valueWhich cache is stored in, it needs to be named to distinguish
keyStored key, usually subject to parameters
conditionCache condition, that is, what conditions are needed to trigger the cache, such as age>20 before the cache record

Here key usually refers to the parameter list, there are two types, you need to add # reference, one is to directly take the variable, the other is to take a variable in the entity class for processing

[External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-UAIK0hzz-1622509750022)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\ image-20210520172547762.png)]

@CachePut annotation

The executed method does not check whether it exists in the cache, but stores the result in the cache every time the method is executed. The parameters are the same as those in @Cacheable.

@CacheEvict annotation

The executed method will delete the corresponding cache, and the two new attributes allEntries and beforeInvocation appear in the parameters.

allEntries represents all cache deletions under the corresponding cache

t comment

The executed method will delete the corresponding cache, and the two new attributes allEntries and beforeInvocation appear in the parameters.

allEntries represents all cache deletions under the corresponding cache

beforeInvocation, it means that it will be executed before the method is successfully executed. If it is changed to true, the cache will be deleted even if the method is not executed successfully.