Spring Boot @Cacheble与Ehc​​ache

时间:2018-08-06 08:14:32

标签: java spring-boot ehcache

我正在将Spring Boot与Ehcache一起用于在应用程序中缓存某些数据。 该应用程序是一项REST服务,可缓存一些高使用率的数据。

我们控制器中的代码如下:

@Cacheable("CategoryModels")
  @GetMapping("/category/{companyId}")
  public List<CategoryViewModel> getAllCategories(@PathVariable(value = "companyId", required = true) long companyId,
    @RequestHeader("user") String user) {
//custom code here
}

现在,在某些情况下,用户正在从服务器获取不同的数据集。在上述情况下有人可以解释吗?

如果数据库中的数据发生了更改,我将刷新缓存,程序将自动将更新后的数据更新到

为了刷新缓存,我使用了一种自定义的书面方法:

Cache categoryCache = (Cache) manager.getCache("CategoryModels").getNativeCache();
categoryCache.removeAll();
categoryController.getAllCategories(company.getCompanyId(), null);

在使用和刷新上述其他缓存的其他缓存上,我具有相同的行为。

2 个答案:

答案 0 :(得分:1)

您应该尝试使用:参数化缓存定义:

@Cacheable(value="CategoryModels", key="{ #root.methodName, #companyId, #user.id }")

答案 1 :(得分:0)

可能有两件事。首先,spring提供的默认密钥解析器除了参数名称外不考虑其他任何内容。解决这个问题的最干净的方法是编写自己的同时考虑类和方法的密钥左轮手枪,否则,可能会从碰巧共享相同参数列表的完全不同的方法中获取数据。