温馨提示×

Java @Cacheable怎样配置有效期

小樊
608
2024-07-15 19:52:42
栏目: 编程语言

在使用 @Cacheable 注解时,可以通过设置 cache 的 ttl(time to live)属性来指定缓存的有效期。ttl 属性表示缓存项在缓存中的存活时间,单位为秒。当缓存项超过 ttl 时间没有被访问时,缓存将会被清除。

以下是一个示例:

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
@CacheConfig(cacheNames = "myCache")
public class MyService {

    @Cacheable(key = "#id", ttl = 60) // 设置缓存有效期为60秒
    public String getFromCache(int id) {
        // 在这里实现获取数据的逻辑
        return "Data for id: " + id;
    }
}

在上面的示例中,@Cacheable 注解中设置了 ttl = 60,表示缓存的有效期为60秒。当调用 getFromCache 方法时,如果缓存中已经存在对应的缓存项且未过期,则直接返回缓存的值;如果缓存项已过期或不存在,则执行方法逻辑,并将方法返回值放入缓存中并设置有效期为60秒。

需要注意的是,@Cacheable 注解的 ttl 属性是在 Spring 4.3 版本中引入的,因此确保你的 Spring 版本支持该属性。

0