@Cacheable 过期时间
时间: 2023-11-02 17:57:53 浏览: 57
@Cacheable 注解是Spring框架中用来声明一个方法的返回值应该被缓存起来的注解。它可以应用在方法上,也可以应用在类上。当我们使用 @Cacheable 注解时,Spring会首先检查缓存中是否存在相同 key 的缓存数据,如果存在,则直接从缓存中取出数据返回;如果不存在,则执行方法,并将返回结果存入缓存中。
@Cacheable 注解的过期时间可以通过配置来设置。在 Spring 中,可以通过配置缓存管理器(如 Ehcache、Redis等)来设置缓存的过期策略。
假设我们使用 Ehcache 作为缓存管理器,在 Spring 的配置文件中,可以如下设置过期时间:
```
<cache:annotation-driven />
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehcache"/>
</bean>
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml"/>
</bean>
```
然后,在方法上使用 @Cacheable 注解时,可以通过设置 `expireSeconds` 属性来指定过期时间,单位是秒:
```
@Cacheable(value = "myCache", key = "#key", expireSeconds = 60)
public String getData(String key) {
// 从数据库或其他数据源获取数据的逻辑
}
```
以上示例中,`expireSeconds = 60` 表示缓存数据的过期时间为60秒,60秒后缓存数据会过期,下一次调用方法时,会重新执行方法并将结果存入缓存中。