2015-07-04 38 views
8

我在我的Spring 4.1.4應用程序中使用最新的Ehcache。我所擁有的是:Spring @Cacheable方法與列表

class Contact{ 
    int id; 
    int revision; 
}  

@Cacheable("contacts") 
public List<Contact> getContactList(List<Integer> contactIdList) { 
    return namedJdbc.queryForList("select * from contact where id in (:idlist)", Collections.singletonMap("idlist", contactIdList)); 
} 

@CachePut(value="contact", key = "id") 
public void updateContact(Contact toUpdate) { 
    jdbctemplate.update("update contact set revision = ? where id = ?", contact.getRevision(), contact.getId()); 
} 

我想實現的是,該聯繫人存儲在緩存中,當我再次調用getContactList方法,即所有接觸其id已經緩存從檢索緩存和其他應該正常查詢,然後緩存。該緩存應該在更新時更新緩存的聯繫人實體。

我使用普通的Spring JDBC和Ehcache,沒有JPA,也沒有Hibernate。

回答

0

不要以爲這是可能的。 List<Integer>將被保存在緩存中,將對應的返回值getContactList的關鍵字保存起來。

因此,除非輸入到您的getContactList的ID的列表包含與以前調用中的ID完全相同的ID,否則它將是緩存未命中,並且將從數據庫中提取數據。 (注:兩個列表被認爲是相等的,如果他們正好包含相同的元素,並以相同的順序)

一個選項是改變你的方法getContactList(List<Integer> contactIdList)getContact(Integer id) - 在這種情況下,它可能需要一段時間來構建高速緩存,但一旦聯繫對於給定的ID在高速緩存中,DB將不會用於在未來的調用中重新獲取它。

儘管不夠優雅,但另一種選擇是在getContactList方法中手動執行緩存。

相關問題