溫馨提示×

Java @Cacheable怎樣配置有效期

小樊
1124
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女