Spring Boot缓存列表

huangapple go评论113阅读模式
英文:

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 = &quot;apps&quot;)
@Scheduled(cron = &quot;0 0/30 * * * ?&quot;)
@CacheEvict(value = &quot;apps&quot;)
public List&lt;Apps&gt; findLatestApps() {
List&lt;Apps&gt; apps = entityManager.createNamedQuery(&quot;AppsQuery&quot;, Apps.class).getResultList();
...
return Apps;

}

This is where i call list method;

public ResponseEntity&lt;AppsResponse&gt; getLatestApps(@PathVariable String name) throws ResourceNotFoundException {
        AppsDto appsDto = appsService.findLatestApps(name);
        return new ResponseEntity&lt;&gt;(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 = &quot;apps&quot;)
public List&lt;Apps&gt; findLatestApps() {
    List&lt;Apps&gt; apps = entityManager.createNamedQuery(&quot;AppsQuery&quot;, Apps.class).getResultList();
    ...
    return apps;
}

@Scheduled(cron = &quot;0 0/30 * * * ?&quot;)
@CacheEvict(value = &quot;apps&quot;)
public void clearAppsCache() {
}

huangapple
  • 本文由 发表于 2020年7月31日 22:38:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/63193945.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定