1. 程式人生 > >Spring快取註解@Cache,@CachePut , @CacheEvict,@CacheConfig使用

Spring快取註解@Cache,@CachePut , @CacheEvict,@CacheConfig使用

@Cacheable、@CachePut、@CacheEvict 註釋介紹

表 1. @Cacheable 作用和配置方法
@Cacheable 的作用 主要針對方法配置,能夠根據方法的請求引數對其結果進行快取
@Cacheable 主要的引數
value 快取的名稱,在 spring 配置檔案中定義,必須指定至少一個 例如:
@Cacheable(value=”mycache”) 或者 
@Cacheable(value={”cache1”,”cache2”}
key 快取的 key,可以為空,如果指定要按照 SpEL 表示式編寫,如果不指定,則預設按照方法的所有引數進行組合 例如:
@Cacheable(value=”testcache”,key=”#userName”)
condition 快取的條件,可以為空,使用 SpEL 編寫,返回 true 或者 false,只有為 true 才進行快取 例如:
@Cacheable(value=”testcache”,condition=”#userName.length()>2”)
------------------------------------------------------------
--////////////////////////////////////////////////////////////////////////////////
表 2. @CachePut 作用和配置方法
@CachePut 的作用 主要針對方法配置,能夠根據方法的請求引數對其結果進行快取,和 @Cacheable 不同的是,它每次都會觸發真實方法的呼叫
@CachePut 主要的引數
value 快取的名稱,在 spring 配置檔案中定義,必須指定至少一個 例如:
@Cacheable(value=”mycache”) 或者 
@Cacheable(value={”cache1”,”cache2”}
key 快取的 key,可以為空,如果指定要按照 SpEL 表示式編寫,如果不指定,則預設按照方法的所有引數進行組合 例如:
@Cacheable(value=”testcache”,key=”#userName”)
condition 快取的條件,可以為空,使用 SpEL 編寫,返回 true 或者 false,只有為 true 才進行快取 例如:
@Cacheable(value=”testcache”,condition=”#userName.length()>2”)
//////////////////////////////////////////////////////
表 3. @CacheEvict 作用和配置方法
@CachEvict 的作用 主要針對方法配置,能夠根據一定的條件對快取進行清空
@CacheEvict 主要的引數
value 快取的名稱,在 spring 配置檔案中定義,必須指定至少一個 例如:
@CachEvict(value=”mycache”) 或者 
@CachEvict(value={”cache1”,”cache2”}
key 快取的 key,可以為空,如果指定要按照 SpEL 表示式編寫,如果不指定,則預設按照方法的所有引數進行組合 例如:
@CachEvict(value=”testcache”,key=”#userName”)
condition 快取的條件,可以為空,使用 SpEL 編寫,返回 true 或者 false,只有為 true 才清空快取 例如:
@CachEvict(value=”testcache”,
condition=”#userName.length()>2”)
allEntries 是否清空所有快取內容,預設為 false,如果指定為 true,則方法呼叫後將立即清空所有快取 例如:
@CachEvict(value=”testcache”,allEntries=true)
beforeInvocation 是否在方法執行前就清空,預設為 false,如果指定為 true,則在方法還沒有執行的時候就清空快取,預設情況下,如果方法執行丟擲異常,則不會清空快取 例如:
@CachEvict(value=”testcache”,beforeInvocation=true)

-------------- 額外補充:@cache(“something");這個相當於save()操作,@cachePut相當於Update()操作,只要他標示的方法被呼叫,那麼都會快取起來,而@cache則是先看下有沒已經快取了,然後再選擇是否執行方法。@CacheEvict相當於Delete()操作。用來清除快取用的。 這寫配置的宣告需要配置好了@enableCache才有用,具體的配置可以看這篇文章 http://blog.csdn.net/sanjay_f/article/details/47363845 -------------
importorg.springframework.stereotype.Service;
importcom.springcache.annotation.Cacheable;
@Service
@Cacheable
public class MemcachedService{
  @Cacheable(name="remote",key="'USER_NAME_'+#args[0]")
public String storeUserName(String accountId,String name)
{
  return name;
}
  @Cacheable(name="remote")
 public String storeUserAddress(String accountId,String address){
   return address;
  }
}


不知道你們注意到一個問題沒有,就是所有的@Cacheable()裡面都有一個name=“xxx”的屬性,這顯然如果方法多了,寫起來也是挺累的,如果可以一次性宣告完 那就省事了, 所以,有了@CacheConfig這個配置,@CacheConfig is a class-level annotation that allows to share the cache names,不過不用擔心,如果你在你的方法寫別的名字,那麼依然以方法的名字為準。
@CacheConfig("books")
public class BookRepositoryImpl implements BookRepository {

    @Cacheable
    public Book findBook(ISBN isbn) {...}
}


當然還有另外一個情況,@Cacheable(name="remote",key="'USER_NAME_'+#args[0]" ,conditional=“xxx”,allEntries=true,beforeInvocation=true) ,像這樣的配置就很長,
@Cacheable(name="book", key="#isbn",conditional=“xxx”,allEntries=true,beforeInvocation=truepublic Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
這樣的配置很長,而且有可能宣告在很多個方法的,所以我們很想精簡點,容易配置些。所以
@findBookByIsbnervice
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)

新建一個檔案findBookByIsbn, 內容如下
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Cacheable(cacheNames="books", key="#isbn")public@interfacefindBookByIsbn {
}
-------------------------------

Features summary

For those who are familiar with Spring’s caching annotations, the following table describes the main differences between the Spring annotations and the JSR-107 counterpart:

Table 35.3. Spring vs. JSR-107 caching annotations

Spring JSR-107 Remark

@Cacheable

@CacheResult

Fairly similar. @CacheResult can cache specific exceptions and force the execution of the method regardless of the content of the cache.

@CachePut

@CachePut

While Spring updates the cache with the result of the method invocation, JCache requires to pass it as an argument that is annotated with @CacheValue. Due to this difference, JCache allows to update the cache before or after the actual method invocation.

@CacheEvict

@CacheRemove

Fairly similar. @CacheRemove supports a conditional evict in case the method invocation results in an exception.

@CacheEvict(allEntries=true)

@CacheRemoveAll

See @CacheRemove.

@CacheConfig

@CacheDefaults

Allows to configure the same concepts, in a similar fashion.

-------------- 關於異常

JCache can manage exceptions thrown by annotated methods:

this can prevent an update of the cache but it can also cache the exception as an indicator of the failure instead of calling the method again. 

Let’s assume that InvalidIsbnNotFoundException is thrown if the structure of the ISBN is invalid.

This is a permanent failure, no book could ever be retrieved with such parameter. 

The following caches the exception so that further calls with the same,

invalid ISBN, throws the cached exception directly instead of invoking the method again.

@CacheResult(cacheName="books", exceptionCacheName="failures"
             cachedExceptions = InvalidIsbnNotFoundException.class)
public Book findBook(ISBN isbn)