【@Cacheable的使用,及设置过期时间 配置方式】

@Cacheable的使用,及设置过期时间 配置方式

使用方式

@Cacheable(cacheNames = “ssss#30” ,key = “#aaa+‘‘+#beginTime+’’+#endTime”)

在这里插入图片描述

cacheNames/value :用来指定缓存组件的名字

key :缓存数据时使用的 key,可以用它来指定。默认是使用方法参数的值。(这个 key 你可以使用 spEL 表达式来编写)

keyGenerator :key 的生成器。 key 和 keyGenerator 二选一使用

cacheManager :可以用来指定缓存管理器。从哪个缓存管理器里面获取缓存。

condition :可以用来指定符合条件的情况下才缓存

unless :否定缓存。当 unless 指定的条件为 true ,方法的返回值就不会被缓存。当然你也可以获取到结果进行判断。(通过 #result 获取方法结果)

sync :是否使用异步模式。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
@Cacheable 注解是用来标记一个方法的结果可以被缓存起来,在下一次调用该方法时,如果缓存中已经存在该结果,则直接从缓存中获取,而不再执行方法体中的逻辑。 然而,@Cacheable 注解本身并不支持直接设置缓存过期时间。它默认使用的是缓存管理器(Cache Manager)中配置过期策略。 要设置具体的过期时间,可以使用具体的缓存管理器,在 Spring Boot 中常用的缓存管理器是基于 Spring Cache 抽象的实现,比如 Ehcache、Redis 等。 以使用 Ehcache 为例,首先需要在 pom.xml 文件中添加 Ehcache 的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> ``` 然后,在 application.properties 文件中配置 Ehcache 的相关属性: ```properties spring.cache.type=ehcache # Ehcache 配置文件路径 spring.cache.ehcache.config=classpath:ehcache.xml ``` 接下来,创建一个名为 ehcache.xml 的文件,并配置缓存过期时间: ```xml <config xmlns="http://www.ehcache.org/v3" xmlns:jsr107="http://www.ehcache.org/v3/jsr107"> <cache alias="myCache" uses-template="myCacheTemplate"> <expiry> <!-- 设置过期时间为 10 秒 --> <ttl unit="seconds">10</ttl> </expiry> </cache> <template name="myCacheTemplate"> <jsr107:cache-template> <jsr107:expiry> <jsr107:ttl unit="seconds">300</jsr107:ttl> </jsr107:expiry> </jsr107:cache-template> </template> </config> ``` 最后,在需要缓存的方法上添加 @Cacheable 注解,并指定缓存的名称: ```java @Cacheable("myCache") public Object getResult() { // 方法体逻辑 } ``` 这样就可以实现根据设定的过期时间进行缓存的自动失效和更新了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值