如何在 Spring Boot 中通过方法参数缓存?

How can I cache by method parameter in Spring Boot?

我使用Redis做缓存,服务方式如下:

@Cacheable(value = "productCache")
@Override
public List<ProductDTO> findAllByCategory(Category category) {
    
    // code omitted 

    return productDTOList;
}

当我将 categoryA 传递给此方法时,结果会被缓存并在有效期内保留。如果我将 categoryB 传递给此方法,它会从数据库中检索,然后保存在缓存中。然后,如果我再次传递 categoryA,它会从缓存中检索。

1.不知道是不是正常的,因为我只是用了@Cacheable注解的value参数(“productCache”),有不知道它如何分别缓存 categoryAcategoryB 结果。你能解释一下它是如何工作的吗?

2. 正如this page中提到的,还有key参数。但是如下图使用时,我觉得没有任何意义,和上面一样工作。这是正常现象还是我遗漏了什么?

@Cacheable(value = "productCache", key="#category")
@Override
public List<ProductDTO> findAllByCategory(Category category) {
    
    // code omitted 

    return productDTOList;
}

3. 我应该通过 Cache cache = cacheManager.getCache("productCache#" + category); 获取缓存吗?

缓存本质上是键值存储,其中 – 在 Spring –

  • 密钥是从方法参数
  • 生成的
  • 是方法调用的结果

默认的密钥生成算法是这样工作的(取自Spring docs):

  • If no params are given, return SimpleKey.EMPTY.
  • If only one param is given, return that instance.
  • If more than one param is given, return a SimpleKey that contains all parameters.

This approach works well for most use-cases, as long as parameters have natural keys and implement valid hashCode() and equals() methods. If that is not the case, you need to change the strategy.

因此在您的示例中,category 对象默认充当键(为此,Category class 应该具有 hashCode()equals() 正确实施)。因此写 key="#category" 是多余的,没有任何效果。如果您的 Category class 会有 id 属性,您可以写 key="#category.id"

Should I get cache via Cache cache = cacheManager.getCache("productCache#" + category); ?

不,因为没有这样的缓存。您只有一个名为 productCache.

的缓存