一、幾個重要概念&緩存注解
Cache | 緩存接口,定義緩存操作。實作有:RedisCache、EhCacheCache、ConcurrentMapCache等 |
CacheManager | 緩存管理器,管理各種緩存(Cache)元件 |
@Cacheable | 主要針對方法配置,能夠根據方法的請求參數對其結果進行緩存 |
@CacheEvict | 清空緩存 |
@CachePut | 保證方法被調用,又希望結果被緩存。 |
@EnableCaching | 開啟基于注解的緩存 |
keyGenerator | 緩存資料時key生成政策 |
serialize | 緩存資料時value序列化政策 |
二、@Cacheable/@CachePut/@CacheEvict 主要的參數
@Cacheable/@CachePut/@CacheEvict 主要的參數 | ||
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”) |
allEntries (@CacheEvict ) | 是否清空所有緩存内容,預設為 false,如果指定為 true,則方法調用後将立即清空所有緩存 | 例如: @CachEvict(value=”testcache”,allEntries=true) |
beforeInvocation (@CacheEvict) | 是否在方法執行前就清空,預設為 false,如果指定為 true,則在方法還沒有執行的時候就清空緩存,預設情況下,如果方法執行抛出異常,則不會清空緩存 | 例如: @CachEvict(value=”testcache”,beforeInvocation=true) |
unless (@CachePut) (@Cacheable) | 用于否決緩存的,不像condition,該表達式隻在方法執行之後判斷,此時可以拿到傳回值result進行判斷。條件為true不會緩存,fasle才緩存 | 例如: @Cacheable(value=”testcache”,unless=”#result == null”) |
三、緩存中SpEL表達式用法
名字 | 位置 | 描述 | 示例 |
methodName | root object | 目前被調用的方法名 | #root.methodName |
method | root object | 目前被調用的方法 | #root.method.name |
target | root object | 目前被調用的目标對象 | #root.target |
targetClass | root object | 目前被調用的目标對象類 | #root.targetClass |
args | root object | 目前被調用的方法的參數清單 | #root.args[0] |
caches | root object | 目前方法調用使用的緩存清單(如@Cacheable(value={"cache1", "cache2"})),則有兩個cache | #root.caches[0].name |
argument name | evaluation context | 方法參數的名字. 可以直接 #參數名 ,也可以使用 #p0或#a0 的形式,0代表參數的索引; | #iban 、 #a0 、 #p0 |
result | evaluation context | 方法執行後的傳回值(僅當方法執行之後的判斷有效,如‘unless’,’cache put’的表達式 ’cache evict’的表達式beforeInvocation=false) | #result |