Springboot RedisCacheManager 类的配置 指定key的过期时间 并在配置文件里配置

目的&效果

在springBoot中配置了RedisCache,当使用@Cacheable注解时,默认为redisCache,通过在配置文件里设置不同key的过期时间,达到可自定义key过期时间的效果。

方案
step 1

新建一个Map类,用于存放要设置的key

@ConfigurationProperties

public class Properties {

    private final Map<String, Duration> initCaches = Maps.newHashMap();

    public Map<String, Duration> getInitCaches() {

        return initCaches;

    }

}

step2

在redis配置类里编写cacheManager,并将map set进去

@Autowired

private Properties properties;

@Bean

public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {

    RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()

            .entryTtl(Duration.ofMinutes(10)).disableCachingNullValues();

    RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);

    ImmutableSet.Builder<String> cacheNames = ImmutableSet.builder();

    ImmutableMap.Builder<String, RedisCacheConfiguration> cacheConfig = ImmutableMap.builder();

    for (Map.Entry<String, Duration> entry : properties.getInitCaches().entrySet()) {

        cacheNames.add(entry.getKey());

        cacheConfig.put(entry.getKey(), defaultCacheConfig.entryTtl(entry.getValue()));

    }

    return RedisCacheManager.builder(redisCacheWriter)

            .cacheDefaults(defaultCacheConfig)

            .initialCacheNames(cacheNames.build())

            .withInitialCacheConfigurations(cacheConfig.build())

            .build();

}

step3
在Springboot yml文件里配置相关的key的过期时间 就可以指定@Cacheable的value的过期时间

//伪代码

@Cacheable(cacheNames = "fooboo", key = "#xxx", unless = "#result == null")

public void fooboo(String xxx){}

applicaion.yml文件中设置

initCaches:

  fooboo: 10m

  fooboo1: 1h

则在redis缓存中fooboo的值,10分钟过期,fooboo1的值1小时过期

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。