12-SpringCache常用注解介绍+框架案例实战

395 阅读3分钟

上一章介绍了什么是Mybatis-plus和SpringCache,并使用SpringBoot对这两个进行了整合,整合完成后编写CRUD接口进行测试,算是初步对Mybatis-plus初步了解,下面我们在了解一下SpringCache。

在本章我们会学习到SpringCache的常用注解,介绍注解的属性和使用方法。

SpringCache常用注解详解

在SpringBoot中也有许多的注解,每个注解都有不一样的功能,在SpringCache也是如此,下面重点了解一下几个常用的注解。

@Cacheable注解在方法上,表示被注解的该方法的返回结果是可以缓存的。也就是说添加该注解在方法上后,该方法的返回结果会存放到缓存当中,以便以后使用相同的参数调用该方法的时候,会返回缓存中的值,而不需要实际的该方法。

@Cacheable注解的属性:

(1)value:缓存名称(可以有多个)

(2)key:缓存key规则,可以使用SpringEL表达式

(3)condition:SpringEL表达式,结果为true,缓存数据到redis。结果为false,不缓存数据到redis.

//对象
@Cacheable(value = {"product"},key="#root.methodName")
//分⻚使用拼接方式
@Cacheable(value ={"product_page"},key="#root.methodName + #page+'_'+#size")

SpringCache框架自定义CacheManager配置和过期时间

当方法中的数据缓存到Redis中时,不可能让数据永久存在这是不现实的,所以我们可以配置缓存的过期时间。下面配置了好几种过期时间分别有1小时与1天,instanceConfig方法是接收传递过来的过期时间配置过期时间。当有方法要使用缓存的过期方法时,在@Cacheable注解体中添加cacheManager="方法名"即可,@Primary是使用默认的过期方法。

 @Bean
    @Primary
    public RedisCacheManager cacheManager1Hour(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration config = instanceConfig(3600L);
        return RedisCacheManager.builder(connectionFactory)
                        .cacheDefaults(config)
                        .transactionAware()
                        .build();
    }
    @Bean
    public RedisCacheManager cacheManager1Day(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration config = instanceConfig(3600 * 24L);
        return RedisCacheManager.builder(connectionFactory)
                        .cacheDefaults(config)
                        .transactionAware()
                        .build();
    }
    private RedisCacheConfiguration instanceConfig(Long ttl) {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();

        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.registerModule(new JavaTimeModule());
        // 去掉各种@JsonSerialize注解的解析

        objectMapper.configure(MapperFeature.USE_ANNOTATIONS, false);
        // 只针对⾮空的值进⾏序列化

        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // 将类型序列化到属性json字符串中

        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance ,
                ObjectMapper.DefaultTyping.NON_FINAL,
                JsonTypeInfo.As.PROPERTY);

        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        return RedisCacheConfiguration.defaultCacheConfig()
                        .entryTtl(Duration.ofSeconds(ttl))
                        .disableCachingNullValues()
                        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer));
    }

SpringCache框架自定义缓存KeyGenerator

一般在团队中为了开发方便与规范,通常会自定义个缓存key作为区分起来方便维护管理。使用方法也很简单,在@Cacheable注解体中,添加keyGenerator="方法名",注意keyGenerator和key不能同时存在。

@Bean
 public KeyGenerator
springCacheDefaultKeyGenerator(){
 return new KeyGenerator() {
 @Override
 public Object generate(Object o,Method method, Object... objects) {
 return o.getClass().getSimpleName() + "_"+ method.getName() +"_"+ StringUtils.arrayToDelimitedString(objects,"_");
 }
 };
 }

SpringCache框架@CachePut实战

@CachePut注解应用在写数据的方法上,比如:新增/修改方法,调用时会自动把相应的数据放入到缓存中,该注解的参数与@Cacheable注解类似

上面有说@CachePut注解是用于更新操作的,使用方法跟@Cacheble类似的,使用案例如下所示:

@CachePut(value = {"product"},key ="#productDO.id")

SpringCache框架@CacheEvict实战

@CacheEvict注解应用在移除数据的方法上,比如:删除方法,调用方法时会从缓存中移除相应的数据

注意:该注解的beforelnvocation=true/false,表示缓存的清除是否是在方法前执行,默认代表缓存清除操作是在方法执行之后执行,如果出现异常的话就不会清除。

@CacheEvict(value = {"product"},key ="#root.args[0]")

SpringCache框架@Caching实战

@Caching注解支持多个注解,有的时候在操作一个方法的时候会涉及到多个注解的使用,这时@Caching注解就起到了作用。

@Caching(
 cacheable = {@Cacheable(value ="product",keyGenerator = "xdclassKeyGenerator")},
 put = {@CachePut(value ="product",key = "#id"),
 @CachePut(value ="product",key = "'stock:'+#id")
 }
 )

本章小结:

通过本章能够较为清晰的认识到SpringCache注解的使用场景与使用方法,在方法中返回数据就存到缓存中,对项目的调优具有举足轻重的作用。