2014-10-31 94 views
1

我使用cache2k作爲我的java應用程序的緩存。cache2k cachesource使用mysql作爲後端

如果緩存不在in-mermoy緩存中,我使用CacheSource進行get和peek請求。 但現在我想實施的方法。

  1. 如何限制內存高速緩存爲例如1000個項目(可選:有時間)?
  2. 我怎樣才能把一個項目到內存和mysql?只需添加一個put方法到cachesource? (MySQL是永久緩存)

希望有人能幫助我。

private static Cache<String, Integer> c = 
      CacheBuilder.newCache(String.class, Integer.class) 
      .source(new CacheSource<String, Integer>() { 
       public Integer get(String o) { 
       System.out.println("ACCESSING SOURCE"); 
       return checkCache(o) ? 1: 0; // checkCache checks if the item is in MySQL Cache 
       } 
      }) 
      .name("cache") 
      .build(); 

回答

2

對於第一個問題,你需要添加兩行:

private static Cache<String, Integer> c = 
    CacheBuilder.newCache(String.class, Integer.class) 
    .name("cache") 
    .maxSize(1000) // limits in memory cache to 1000 entries 
    .expirySecs(60) // sets expiry (time to live) to 60 seconds 
    .source(new CacheSource<String, Integer>() { 
     public Integer get(String o) { 
     System.out.println("ACCESSING SOURCE"); 
     return checkCache(o) ? 1: 0; 
     } 
    }) 
    .build(); 

兩個提示上expirySecs:默認情況下cache2k有10分鐘的默認過期。您可以使用expirySecs(-1)切換到期。即將推出的cache2k版本0.20將清除界面:eternal(true)將切換到期。而expiryDuration(long, Timeunit)是設置到期時間的新方法。方法expiryMillisexpirySecs仍然存在並受支持,但在更高版本中會消失。

第二個問題:爲了把一個進入與連接mysql的持久性緩存,請使用此模式:

start database transaction 
update item in the database 
cache.remove(item key) 
commit the transaction 

通過get()下一個高速緩存訪​​問將是一個小姐,調用緩存源和取來自數據庫的更新元素。如果一個get()發生在remove()和數據庫提交之間,它會停滯,直到事務提交(這實際上取決於你的mysql設置和事務隔離級別)。如果您希望將cache2k用作數據庫持久層的緩存,則此模式也適用。

使用cache.put然後將該元素插入到數據庫導致併發問題,因爲這兩個操作不是原子的。上述模式更安全,但速度更慢,因爲對於每個緩存更新,都需要數據庫存儲和提取。

另一個提示:做到這一點的「最佳途徑」將在未來發生變化。我現在正在爲cache2k添加一般持久性支持。所以這將只是未來添加數據庫屬性的問題。