2017-03-22 29 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