英文:
Spring Boot Cache List
问题
以下是翻译好的部分:
我有一个方法,它返回一个列表。列表变量来自数据库,有时数据会更新,所以我想要缓存列表,但是例如每半小时我想要清除缓存。如何使用Cacheable和CacheEvict方法来做到这一点呢?我尝试在同一个方法中使用它们作为注解,但它没有起作用,而且我没有其他地方可以调用它们,除了这个方法。
@Cacheable(value = "apps")
@Scheduled(cron = "0 0/30 * * * ?")
@CacheEvict(value = "apps")
public List<Apps> findLatestApps() {
List<Apps> apps = entityManager.createNamedQuery("AppsQuery", Apps.class).getResultList();
...
return Apps;
}
这是我调用列表方法的地方:
public ResponseEntity<AppsResponse> getLatestApps(@PathVariable String name) throws ResourceNotFoundException {
AppsDto appsDto = appsService.findLatestApps(name);
return new ResponseEntity<>(new ModelMapper().map(appsDto, AppsResponse.class), HttpStatus.OK);
}
英文:
I have a method which returns list. List variables are coming from database and sometimes data is updating so i want to cache list but for example in every half an hour i want to clear the cache. How can i do this with Cacheable and CacheEvict method? I tried to use them in same method as annotation but it didn't work and i have nowhere to call them other than this method.
@Cacheable(value = "apps")
@Scheduled(cron = "0 0/30 * * * ?")
@CacheEvict(value = "apps")
public List<Apps> findLatestApps() {
List<Apps> apps = entityManager.createNamedQuery("AppsQuery", Apps.class).getResultList();
...
return Apps;
}
This is where i call list method;
public ResponseEntity<AppsResponse> getLatestApps(@PathVariable String name) throws ResourceNotFoundException {
AppsDto appsDto = appsService.findLatestApps(name);
return new ResponseEntity<>(new ModelMapper().map(appsDto, AppsResponse.class), HttpStatus.OK);
}
答案1
得分: 4
你不能在同一个方法中执行这个操作。因为该方法应该做什么?缓存还是清除?
@Cacheable(value = "apps")
public List<Apps> findLatestApps() {
List<Apps> apps = entityManager.createNamedQuery("AppsQuery", Apps.class).getResultList();
...
return apps;
}
@Scheduled(cron = "0 0/30 * * * ?")
@CacheEvict(value = "apps")
public void clearAppsCache() {
}
英文:
You can't do this in the same method. Because what should the method do? Cache or Evict?
@Cacheable(value = "apps")
public List<Apps> findLatestApps() {
List<Apps> apps = entityManager.createNamedQuery("AppsQuery", Apps.class).getResultList();
...
return apps;
}
@Scheduled(cron = "0 0/30 * * * ?")
@CacheEvict(value = "apps")
public void clearAppsCache() {
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论