【问题标题】:My cache is not updated using @CachePut annotation我的缓存没有使用 @CachePut 注释更新
【发布时间】:2020-09-09 02:45:27
【问题描述】:

我搜索了为什么@CachePut 没有在我的缓存中插入数据的问题,但我没有让它工作。

@Cacheable(value = "employee")
public Map<String, String> getAllEmployeeIdWithFullNames() {
    return employeeRepo.getAllEmployeeIdWithFullNames();
}

我使用了@CachePut,如下所示:

@CachePut(value = "employee") 
Map<String, String> saveEmployee(Employee employee) {
    Map<String, String> employeeDetail = new HashMap<>();
    employeeRepo.save(employee);
    employeeDetail.put(employee.getUserId(), employee.getDisplayName());
    return employeeDetail;
}

【问题讨论】:

  • 它工作得很好,只有你对它的工作原理的理解是有缺陷的。第一个调用将缓存一个包含所有结果的映射,另一个将缓存一个带有单个结果的映射,作为键。所以这两种方法缓存不同的东西,显然它不会覆盖或更新缓存中的单个元素。这不是缓存抽象的工作方式。
  • @M.Deinum 感谢您的回复,所以我需要将新结果添加到现有缓存值中,然后在第二种情况下返回吗?
  • 如果你想自己控制缓存,那就自己做缓存。否则,您将在工作/与不应该使用的东西作斗争。您仍然可以注入 Cache 并使用它。或者只是清除缓存,当调用getAllEmployeeIdWithFullNames时会再次填充。
  • 您在哪里定义您将使用的Cache?你的实现是什么?
  • @MarioCodes 我使用的是启用缓存后的默认缓存,我没有配置任何 CacheManager,例如 EHCache 等。

标签: java spring spring-boot caching


【解决方案1】:

我测试了它,它工作正常。只是正如 Deinum 所说,您缓存了两种不同的东西。

方法getAllEmployeeIdWithFullNames() 返回一个Map&lt;String, String&gt;,其中包含所有员工Map

saveEmployee(Employee employee) 方法返回 另一个 Map&lt;String, String&gt;,其中包含一个Map 包含 1 名员工的详细信息

它们都是相同的对象类型 Map&lt;String, String&gt;,但它们不是同一个东西。我的建议是为 2 种不同的事物使用 2 种不同的缓存。 employeesDetails 缓存用于详细信息,allEmployees 缓存用于您的所有员工

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 2019-02-25
    • 2013-07-17
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多