spring 緩衝 @CachePut 和 @Cacheable 區別

來源:互聯網
上載者:User

spring 緩衝 @CachePut 和 @Cacheable 區別

首先這兩個的區別是:

@CachePut:這個注釋可以確保方法被執行,同時方法的傳回值也被記錄到緩衝中。

@Cacheable:當重複使用相同參數調用方法的時候,方法本身不會被調用執行,即方法本身被略過了,取而代之的是方法的結果直接從緩衝中找到並返回了。

那麼對於@CachePut這個註解,它的作用是什麼呢,每次方法都執行,那麼緩衝的意義是什麼呢?在這裡寫了一個小執行個體對這兩個標籤進行測試,並解釋了上邊這個疑問。

首先,我們猜想對於同一個緩衝執行個體的相同的key的緩衝的資料,可以用@CachePut更新,而@Cacheable在取值的時候,是@CachePut更新後的值。

先看看service:

 

@Cacheable(value="userCache",key="1000")public String getUserByName(String userName) {    System.out.println("兩次調用第一次會執行,第二次不會執行!");   return getFromDB(userName); } @CachePut(value="userCache",key="1000")public String updateUserPut(String userName) {   return updateDB(userName); } 

注意這裡的key定義的都是1000,緩衝的執行個體都是userCache

 

測試方法:

 

// 載入 spring 設定檔    ApplicationContext context = new ClassPathXmlApplicationContext("com/spricache/config/spring-cache.xml");    UserService userService = (UserService) context.getBean("userService");     //會查詢資料庫    System.out.println(userService.getUserByName("txxs"));    //會走緩衝    System.out.println(userService.getUserByName("txxs"));    //更新名字,會走資料庫    System.out.println(userService.updateUserPut("txxsNew"));    //會走緩衝呢,還是資料庫呢?    System.out.println(userService.getUserByName("txxsNew"));

執行的結果:

 

兩次調用第一次會執行,第二次不會執行!
正在從資料庫查詢txxs
txxs
txxs
更新資料庫txxsNew
txxsNew
txxsNew

我們來分析這個結果:System.out.println(userService.getUserByName("txxs"));被執行兩次,第一次是從資料庫中取值,第二次是從緩衝中取值,這和我們之前所瞭解的緩衝用法是一樣的。那麼我們調用System.out.println(userService.updateUserPut("txxsNew"));這個方法會更新資料庫中的名字,注意這裡的key值我們定義的是1000,也就是會更新userCache中key為1000的值,然後將會返回的結果,這裡我們也做了一個輸出操作,也就是第一個txxsNew。然後再調用System.out.println(userService.getUserByName("txxsNew"));擷取key為1000的名字,輸出的結果是txxsNew,正是updateUserPut方法更新後的緩衝的值。

總結:@CachePut和@Cacheable這兩個標籤可以結合使用,當需要根據請求改變值的時候,利用@CachePut將值改變並寫入到緩衝中,而@Cacheable標籤除了第一次之外,一直是取的緩衝的值。注意結合使用時需要注意兩點:

1、必須是同一個緩衝執行個體。

2、key值必須是相同的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.