gpt4 book ai didi

spring - 如何在 spring 中缓存对象列表?

转载 作者:行者123 更新时间:2023-12-05 06:31:07 24 4
gpt4 key购买 nike

我有一个名为 getUserById 的方法

@Cacheable(value = "Account", key = "#accountId")
public Account getUserById(Long accountId) {

还有另一个叫做 getUserByIds 的方法

@Cacheable(?????)
public List<Account> getUserByIds(List<Long> accountIds) {

如何通过帐户 ID 缓存所有帐户?谢谢

最佳答案

实际上你根本不需要为@Cacheable指定key

在我的例子中,我需要从 repo 中读取一个集合并将其存储在内存中,以便通过列表进行后续迭代。

@Cacheable("users")
public List<RegionPercentage> getUserByIds(List<Long> accountIds) {
return repository.getUsers();
}

使用此方法,我的方法每次都从缓存中返回列表,而不是调用存储库。

因此,为了更新缓存,我设法使用 cron 自动清除它(在我的例子中,每 30 秒一次以查看差异)

@Scheduled(cron = "0,30 * * * * ?")
@CacheEvict(value = "users", allEntries = true)
public void deleteCache() {
// this method can be empty
}

不要忘记在 Spring Boot 应用程序的主类中设置@EnableCaching

关于spring - 如何在 spring 中缓存对象列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51887879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com