2017-03-22 53 views
0

正确标注我有一个这样的模型对象 -为的Ehcache和春季

class ProductDTO { 
    int id; 
    String code; 
    String description; 

    //getters and setters go here 
} 

我想在Web服务中使用Spring 4的Ehcache与这样的代码 -

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

回答

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; 
} 
+0

非常感谢Shubham。我用@CachePut添加了2个方法 - 1代码和另一个代码。我从每个产品的getAllProducts()中调用它们。现在getProductDescriptionInCache()调用getAllProducts() - 在返回的列表中找到正确的描述,并返回并缓存它。如果我使用相同的代码再次调用getProductDescriptionInCache(),它会从缓存中正确提取值,但如果传递不同的代码,即使我缓存getAllProducts()发现的所有产品,也会再次调用getAllProducts()。我错过了什么。 – lenniekid

+0

你可以粘贴你的getProductDescriptionInCache()函数吗? – shubham