如何在缓存中找不到@Cacheable时返回null但不缓存结果?

Pra*_*ate 4 spring caching annotations

关注@Cacheable注释

@Cacheable(value="books", key="#isbn")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
Run Code Online (Sandbox Code Playgroud)
  • 根据密钥在缓存中查找
  • 如果找到则返回缓存中的结果
  • 如果没有找到评估方法
  • 更新缓存
  • 返回结果

因此,下次使用相同的参数调用此方法时,将从缓存中获取该方法.

我想要的只是为了

  • 根据密钥在缓存中查找
  • 如果找到则返回缓存中的结果
  • 如果没有找到则返回null

我不想在cache-miss的情况下更新缓存,有没有办法使用spring Annotation来做到这一点

Pra*_*ate 7

这是我最终得到的,诀窍是使用'除非'对我们有利

@Cacheable(value="books", key="#isbn", unless = "#result == null")
public Book findBookFromCache(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
{
    return null;
}
Run Code Online (Sandbox Code Playgroud)

这种方法

  • 根据密钥在缓存中查找
  • 如果找到则返回缓存中的结果
  • 如果未找到,则计算返回null的方法
  • 返回值与除非条件(总是返回true)匹配
  • null值不会被缓存
  • null值返回给调用者