java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring Caching配置缓存过期时间

Spring Caching配置缓存过期时间详解

作者:tag心动

SpringCache基于AOP,通过注解实现缓存功能,抽象底层框架,默认使用Redis存储,支持多缓存配置,开启需添加注解,配置缓存项可指定过期时间

一、Spring Cache是什么?

它利用了AOP,实现了基于注解的缓存功能,并且进行了合理的抽象,业务代码不用关心底层是使用了什么缓存框架,只需要简单地加一个注解,就能实现缓存功能了。

而且Spring Cache也提供了很多默认的配置,用户可以3秒钟就使用上一个很不错的缓存功能。

工作流程:

特性:

二、使用步骤

开启基于注解的缓存

@EnableCaching

配置缓存

	@Cacheable(value = "DefaultKeyTest", keyGenerator = "simpleKeyGenerator", /*cacheNames = API_DETAIL_KEY_PREFIX, key = "target.redisApiDetailKeyPrefix + ':' + #appCode",*/ unless = "#result == null")
    public OpenApiDetailVo findByAppCode(String appCode) {
        return openApiAuthService.queryDetail(appCode);
    }

三、解决方案

方案一:通过编写config设置缓存相关项

@Configuration
public class RedisCacheConfig {

    @Bean
    public KeyGenerator simpleKeyGenerator() {
        return (o, method, objects) -> {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(o.getClass().getSimpleName());
            stringBuilder.append(".");
            stringBuilder.append(method.getName());
            stringBuilder.append("[");
            for (Object obj : objects) {
                stringBuilder.append(obj.toString());
            }
            stringBuilder.append("]");

            return stringBuilder.toString();
        };
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        return new RedisCacheManager(
                RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
                this.getRedisCacheConfigurationWithTtl(600), // 默认策略,未配置的 key 会使用这个
                this.getRedisCacheConfigurationMap() // 指定 key 策略
        );
    }

    private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
        Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
        redisCacheConfigurationMap.put("UserInfoList", this.getRedisCacheConfigurationWithTtl(3000));
        redisCacheConfigurationMap.put("UserInfoListAnother", this.getRedisCacheConfigurationWithTtl(18000));

        return redisCacheConfigurationMap;
    }

    private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL,
                JsonTypeInfo.As.WRAPPER_ARRAY);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
                RedisSerializationContext
                        .SerializationPair
                        .fromSerializer(jackson2JsonRedisSerializer)
        ).entryTtl(Duration.ofSeconds(seconds));

        return redisCacheConfiguration;
    }
}
	// 3000秒
    @Cacheable(value = "UserInfoList", keyGenerator = "simpleKeyGenerator")
    // 18000秒
    @Cacheable(value = "UserInfoListAnother", keyGenerator = "simpleKeyGenerator")
    // 600秒,未指定的key,使用默认策略
    @Cacheable(value = "DefaultKeyTest", keyGenerator = "simpleKeyGenerator")

方案二:通过配置文件

spring:
  # maximumSize:配置缓存的最大条数,当快要达到容量上限的时候,缓存管理器会根据一定的策略将部分缓存项移除。
  # expireAfterAccess:配置缓存项的过期机制,缓存项固定30秒将会过期,从而被移除。
  cache:
    caffeine:
      spec: maximumSize=500, expireAfterAccess=30s
    type: caffeine

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文