更正 ehcache 和 spring 的注释



我有一个这样的模型对象 -

class ProductDTO {
    int id;
    String code;
    String description;
   //getters and setters go here
}

我正在尝试在具有以下代码的 Web 服务中使用带有 ehcache 的 Spring 4 -

class ProductServiceImpl implements ProductService {
     List<ProductDTO> getAllProducts() {
         //Query to data layer getting all products
     }
     String getProductDescriptionById(int id) {
          //Query to data layer getting product by id
     }
     @Cacheable("prodCache")
     String getProductDescriptionByCode(String code) {
          //Query to data layer getting product by code
     }
}
缓存在

具有可缓存注释的方法 getProductDescriptionByCode(( 上工作正常。每次调用getProductDescriptionById((或getProductDescriptionByCode((时,如果缓存未命中,我想获取所有产品(可能正在使用getAllProducts((,但不一定(并缓存它们,以便下次我可以检索任何产品。我应该对注释或代码进行哪些添加或更改?

因此,

当您使用 getAllProducts(( 检索所有产品时,您需要迭代每个产品并使用 @CachePut 将它们放入缓存中。您需要分离一次缓存放置函数,以按代码放置描述,按 id 放置其他描述。

List<ProductDTO> getAllProducts() {
         List<ProductDTO> productList //get the list from database
         for(ProductDTO product : productList) {
             putProductDescriptionInCache(product.getDescription(), product.getCode());
          }
}
  @CachePut(value = "prodCache", key = "#Code")
   String putProductDescriptionInCache(String description, String Code){
    return description;
}

最新更新