Springboot 注解 @Cacheable自定义单个key设置expire超时时间 并在配置文件里配置

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();

    RedisCacheWrit
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中,你可以使用`@Cacheable`注解与缓存管理器一起设置缓存的过期时间(TTL)。下面是一个示例: 首先,确保在pom.xml中添加了适当的依赖。这以使用Ehcache作为缓存管理器为例,添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> ``` 然后,在Spring Boot的配置文件(如application.properties或application.yml)中,配置缓存的过期时间。例如,使用Ehcache配置示例: ```properties spring.cache.type=ehcache spring.cache.ehcache.config=classpath:ehcache.xml ``` 接下来,在你的Spring Boot应用程序中,使用`@Cacheable`注解来启用缓存,并设置缓存的过期时间。例如: ```java import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class MyService { @Cacheable(value = "myCache", key = "#key", cacheManager = "cacheManager") public Object getData(String key) { // 根据key获取数据的逻辑 } } ``` 在上面的示例中,我们使用`@Cacheable`注解来启用缓存,并设置了缓存的名称为"myCache",缓存管理器为"cacheManager"。`key`参数表示缓存的键,可以根据需要进行设置。 最后,在Ehcache配置文件(ehcache.xml)中,设置缓存的过期时间。例如: ```xml <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd"> <cache name="myCache" maxEntriesLocalHeap="1000" eternal="false" timeToIdleSeconds="60" timeToLiveSeconds="120" memoryStoreEvictionPolicy="LRU" /> </ehcache> ``` 在上面的示例中,我们设置了缓存名称为"myCache",并将`timeToLiveSeconds`属性设置为120,表示缓存的过期时间为120秒。 通过以上步骤,你就可以在Spring Boot中使用`@Cacheable`注解与缓存管理器一起设置缓存的过期时间了。当方法被调用时,如果缓存中存在对应的数据且未过期,则直接从缓存中获取数据,否则会执行方法体逻辑并将返回值存储到缓存中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值