本文是《輕量級 Java Web 框架架構設計》的系列博文。 java
以前實現了一個簡單的 Cache 插件,主要用於 Service 層,爲了減小數據庫的訪問次數,將數據放入 Cache 中緩存起來。在 Service 中直接使用了 Cache API,這樣致使 Service 代碼變得更加複雜,Cache 邏輯與核心邏輯糾纏在一塊兒,我想着應該是一個很明顯的缺點吧。具體的開發過程,請參考《Smart Plugin —— 從一個簡單的 Cache 開始》。 數據庫
後來 Bieber 對 Cache 作了一個優化,結合了 Spring Cache 的註解式配置,讓 Service 中所涉及的 Cache 操做分離出來,充分利用了 AOP 的思想,經過使用 Smart 的 Aspect(切面類)來實現此功能。你們能夠閱讀這篇博文《Smart Framework 緩存插件的實現》。 緩存
我下面打算與你們交流的這樣一個思路: 架構
有些插件,好比:Cache、Log、Performance 等,實際上他們都帶有 AOP 的色彩,都是爲了在執行目標方法的先後分別作點事情。就 Cache 插件而言,它應該本身提供一個 Aspect,並將此 Aspect 融入到 Smart AOP 環境中,而無需在應用程序中,定義一個 Cache 的 Aspect(這樣或許有些多餘)。也就是說,Cache 插件的核心就是一個 Aspect,此外才是用於控制緩存的 API,而這些 API 是給插件自身來調用的,而不是給應用程序調用而已。 框架
我想像這樣來實現緩存: ide
@Bean @Cachable public class CustomerServiceImpl extends BaseService implements CustomerService { @Override @CachePut("customer_list_cache") public List<Customer> getCustomerList() { return DataSet.selectList(Customer.class, null, null); } @Override @CacheClear({"customer_list_cache", "customer_cache"}) public boolean deleteCustomer(long id) { return DataSet.delete(Customer.class, "id = ?", id); } @Override @CachePut("customer_cache") public Customer getCustomer(long id) { return DataSet.select(Customer.class, "id = ?", id); } @Override @CacheClear({"customer_list_cache", "customer_cache"}) public boolean updateCustomer(long id, Map<String, Object> fieldMap) { return DataSet.update(Customer.class, fieldMap, "id = ?", id); } @Override @CacheClear({"customer_list_cache", "customer_cache"}) public boolean createCustomer(Map<String, Object> fieldMap) { return DataSet.insert(Customer.class, fieldMap); } }
在以上代碼中,在類上面使用了 Cachable 註解,說明這個類是具有緩存特性的(可緩存的)。在須要緩存的方法上,使用了 CachePut 註解或 CacheClear 註解,前者用於將數據放入緩存,後者用戶從緩存中清空數據(也就是使緩存消失)。 優化
例如,在 getCustomerList 方法中,使用了 CachePut 註解,在其註解參數中定義了 Cache 名稱(customer_list_cache)。在實際運行時,先從 Cache 裏獲取數據,若是沒有,則從 DB 中獲取,最後將數據放回 Cache 中。這個邏輯都是在 Cache 插件中實現的。 spa
又如,在 deleteCustomer 方法中,使用了 CacheClear 註解,此時定義了兩個 Cache 名稱(customer_list_cache 與 customer_cache)。須要說明的是,這個 Service 中存在兩個 Cache,一個用於緩存 customerList 數據,另外一個用於緩存 customer 數據。當刪除一個 Customer 時,首先在 DB 中進行,而後刷新緩存,此時須要一併刷新所涉及到該 Customer 的全部 Cache,因此這裏在 CacheClear 註解中定義了兩個 Cache。 .net
後面幾個方法與以上兩個方法相似。其實 Cache 要乾的事情,也就這兩個方面(此時沒有考慮 Cache 的淘汰策略)。 插件
個人問題是,這樣的實現感受粒度有些粗,由於控制的在方法級別上,有沒有可能將 Cache 控制在方法的內部呢?實際狀況我想或許會比這個案例複雜,你們認爲這種方式可行嗎?
期待朋友們的解惑......