首页 文章

正确注释ehcache和spring

提问于
浏览
0

我有一个这样的Model对象 -

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()但不一定)并缓存它们以便下次,我可以检索任何产品 . 我应该对注释或代码进行哪些添加或更改?

1 回答

  • 2

    因此,当您使用getAllProducts()检索所有产品时,需要对每个产品进行迭代并使用@CachePut将它们放入缓存中 . 您需要选择一次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;
    }
    

相关问题