W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
public static void main(String[] args) throws Exception { YMP.get().init(); try { // 操作默認緩存 Caches.get().put("key1", "value1"); System.out.println(Caches.get().get("key1")); // 操作指定名稱的緩存 Caches.get().put("default", "key2", "value2"); System.out.println(Caches.get().get("default", "key2")); } finally { YMP.get().destroy(); } }
注:當指定緩存名稱時,請確認與名稱對應的配置是否已存在;
執(zhí)行結果:
value1 value2
這里用到了@Cacheable注解,作用是標識類中方法的執(zhí)行結果是否進行緩存,需要注意的是:
首先@Cacheable注解必須在已注冊到YMP類對象管理器的類上聲明,表示該類支持緩存;
其次,在需要緩存執(zhí)行結果的方法上添加@Cacheable注解;
@Cacheable注解參數說明:
cacheName:緩存名稱, 默認值為default;
key:緩存Key, 若未設置則使用keyGenerator自動生成;
generator:Key生成器接口實現類,默認為DefaultKeyGenerator.class;
scope:緩存作用域,可選值為APPLICATION、SESSION和DEFAULT,默認為DEFAULT,非DEFAULT設置需要緩存作用域處理器(ICacheScopeProcessor)接口配合;
timeout:緩存數據超時時間, 可選參數,數值必須大于等于0,為0表示默認緩存300秒;
示例代碼:
@Bean @Cacheable public class CacheDemo { @Cacheable public String sayHi(String name) { System.out.println("No Cached"); return "Hi, " + name; } public static void main(String[] args) throws Exception { YMP.get().init(); try { CacheDemo _demo = YMP.get().getBean(CacheDemo.class); System.out.println(_demo.sayHi("YMP")); System.out.println(_demo.sayHi("YMP")); // System.out.println("--------"); // System.out.println(_demo.sayHi("YMPer")); System.out.println(_demo.sayHi("YMP")); System.out.println(_demo.sayHi("YMPer")); } finally { YMP.get().destroy(); } } }
執(zhí)行結果:
No Cached Hi, YMP Hi, YMP -------- No Cached Hi, YMPer Hi, YMP Hi, YMPer
以上結果輸出可以看出,sayHi方法相同參數首次被調用時將輸出“No Cached”字符串,說明它沒有使用緩存,再次調用時直接從緩存中返回值;
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯系方式:
更多建議: