Java @Cacheable怎样配置有效期

   2024-10-06 4520
核心提示:在使用 @Cacheable 注解时,可以通过设置 cache 的 ttl(time to live)属性来指定缓存的有效期。ttl 属性表示缓存项在缓存中的

在使用 @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 版本支持该属性。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号