@Cacheable 注解如何设置过期
时间: 2023-11-02 22:57:36 浏览: 57
@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() {
// 方法体逻辑
}
```
这样就可以实现根据设定的过期时间进行缓存的自动失效和更新了。