springcache使用筆記002_注釋驅動的 Spring cache 按條件查詢

來源:互聯網
上載者:User
如何按照條件操作緩衝

前面介紹的緩衝方法,沒有任何條件,即所有對 accountService 對象的 getAccountByName 方法的調用都會起動緩衝效果,不管參數是什麼值,如果有一個需求,就是只有帳號名稱的長度小於等於 4 的情況下,才做緩衝,大於 4 的不使用緩衝,那怎麼實現呢。

Spring cache 提供了一個很好的方法,那就是基於 SpEL 運算式的 condition 定義,這個 condition 是 @Cacheable 注釋的一個屬性,下面我來示範一下 清單 13. AccountService.java(getAccountByName 方法修訂,支援條件)

1 2 3 4 5 @Cacheable(value="accountCache",condition="#userName.length() <= 4")// 緩衝名叫 accountCache public Account getAccountByName(String userName) { // 方法內部實現不考慮緩衝邏輯,直接實現業務 return getFromDB(userName); }

注意其中的 condition=”#userName.length() <=4”,這裡使用了 SpEL 運算式訪問了參數 userName 對象的 length() 方法,條件運算式返回一個布爾值,true/false,當條件為 true,則進行快取作業,否則直接調用方法執行的返回結果。 清單 14. 測試方法

1 2 3 4 s.getAccountByName("somebody");// 長度大於 4,不會被緩衝 s.getAccountByName("sbd");// 長度小於 4,會被緩衝 s.getAccountByName("somebody");// 還是查詢資料庫 s.getAccountByName("sbd");// 會從緩衝返回
清單 15. 運行結果
1 2 3

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.