緩存要解決的問題:一個程序的瓶頸在于數據庫,我們也知道內存的速度是大大快于硬盤的速度的。當我們需要重復地獲取相同的數據的時候,我們一次又一次的請求數據庫或者遠程服務,導致大量的時間耗費在數據庫查詢或者遠程方法調用上,導致程序性能的惡化,這便是數據緩存要解決的問題。
類似的緩存技術有:redis、ehcache、guava等,現在一般常用的為redis。
spring 3.1 引入了激動人心的基于注釋(annotation)的緩存(cache)技術,它本質上不是一個具體的緩存實現方案(例如ehcache 或者 oscache),而是一個對緩存使用的抽象,通過在既有代碼中添加少量它定義的各種 annotation,即能夠達到緩存方法的返回對象的效果。
spring 的緩存技術還具備相當的靈活性,不僅能夠使用 spel(spring expression language)來定義緩存的 key 和各種 condition,還提供開箱即用的緩存臨時存儲方案,也支持和主流的專業緩存例如 ehcache 集成。
其特點總結如下:
1. 通過少量的配置 annotation 注釋即可使得既有代碼支持緩存
2. 支持開箱即用 out-of-the-box,即不用安裝和部署額外第三方組件即可使用緩存
3. 支持 spring express language,能使用對象的任何屬性或者方法來定義緩存的 key 和 condition
4. 支持 aspectj,并通過其實現任何方法的緩存支持
5. 支持自定義 key 和自定義緩存管理者,具有相當的靈活性和擴展性
一、spring boot cache原理
第一步、自動配置類;
自動啟動類:cacheautoconfiguration
屬性配置:cacheproperties
主啟動類添加:@enablecaching注解
cache pom添加:
1
2
3
4
|
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-cache</artifactid> </dependency> |
第二步、從緩存的配置類 中獲取 多個cache
cacheconfigurationimportselector.selectimports()方法獲取
1
2
3
4
5
6
7
8
9
10
11
12
13
|
static class cacheconfigurationimportselector implements importselector { ? @override public string[] selectimports(annotationmetadata importingclassmetadata) { cachetype[] types = cachetype.values(); string[] imports = new string[types.length]; for ( int i = 0 ; i < types.length; i++) { imports[i] = cacheconfigurations.getconfigurationclass(types[i]); } return imports; } ? } |
獲取結果:simplecacheconfiguration 默認cache
1
2
3
4
5
6
7
8
9
10
11
|
org.springframework.boot.autoconfigure.cache.genericcacheconfiguration org.springframework.boot.autoconfigure.cache.jcachecacheconfiguration org.springframework.boot.autoconfigure.cache.ehcachecacheconfiguration org.springframework.boot.autoconfigure.cache.hazelcastcacheconfiguration org.springframework.boot.autoconfigure.cache.infinispancacheconfiguration org.springframework.boot.autoconfigure.cache.couchbasecacheconfiguration org.springframework.boot.autoconfigure.cache.rediscacheconfiguration org.springframework.boot.autoconfigure.cache.caffeinecacheconfiguration org.springframework.boot.autoconfigure.cache.guavacacheconfiguration org.springframework.boot.autoconfigure.cache.simplecacheconfiguration【默認】 org.springframework.boot.autoconfigure.cache.noopcacheconfiguration |
第三步:simplecacheconfiguration.cachemanager()
此方法中給容器中注冊了一個cachemanager組件:類型為concurrentmapcachemanager
1
2
3
4
5
6
7
8
9
|
@bean public concurrentmapcachemanager cachemanager() { concurrentmapcachemanager cachemanager = new concurrentmapcachemanager(); list<string> cachenames = this .cacheproperties.getcachenames(); if (!cachenames.isempty()) { cachemanager.setcachenames(cachenames); } return this .customizerinvoker.customize(cachemanager); } |
第四步:查看獲取緩存方法getcache()
concurrentmapcachemanager 類里,數據都存儲到為concurrentmap 中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public cache getcache(string name) { cache cache = this .cachemap.get(name); //cachemap 為concurrentmap 類型,獲取一個cache組件 if (cache == null && this .dynamic) { synchronized ( this .cachemap) { cache = this .cachemap.get(name); //cahcemap不為空獲取 if (cache == null ) { //可以獲取或者創建concurrentmapcache類型的緩存組件;他的作用將數據保存在concurrentmap中; cache = createconcurrentmapcache(name); this .cachemap.put(name, cache); //concurrentmapcache.lookup(); } } } return cache; } |
二、cacheable運行流程:
? @cacheable: 1、方法運行之前,先去查詢cache(緩存組件),按照cachenames指定的名字獲??; (cachemanager先獲取相應的緩存),第一次獲取緩存如果沒有cache組件會自動創建。 2、去cache中查找緩存的內容(concurrentmapcache.lookup()方法中去查找),使用一個key,默認就是方法的參數; key是按照某種策略生成的;默認是使用keygenerator生成的,默認使用simplekeygenerator生成key; simplekeygenerator生成key的默認策略; 如果沒有參數;key=new simplekey(); 如果有一個參數:key=參數的值 如果有多個參數:key=new simplekey(params);
1
2
3
4
5
6
7
8
9
10
11
12
13
|
//這個方法 simplekeygenerator.generatekey() 方法生成key public static object generatekey(object... params) { if (params.length == 0 ) { return simplekey.empty; } if (params.length == 1 ) { //如果只有一個參數,直接返回這個參數為key object param = params[ 0 ]; if (param != null && !param.getclass().isarray()) { return param; } } return new simplekey(params); } |
3、沒有查到緩存就調用目標方法; 4、將目標方法返回的結果,放進緩存中concurrentmapcache.put();
@cacheable標注的方法執行之前先來檢查緩存中有沒有這個數據,默認按照參數的值作為key去查詢緩存, 如果沒有就運行方法并將結果放入緩存;以后再來調用就可以直接使用緩存中的數據;
? 核心: 1)、使用cachemanager【concurrentmapcachemanager】按照名字得到cache【concurrentmapcache】組件 2)、key使用keygenerator生成的,默認是simplekeygenerator
詳細執行流程:concurrentmapcache.lookup()上斷點查看,執行過程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
//第一步cacheaspectsupport 中execute() private object execute( final cacheoperationinvoker invoker, method method, cacheoperationcontexts contexts) //第二步 cacheaspectsupport private cache.valuewrapper findcacheditem(collection<cacheoperationcontext> contexts) { object result = cacheoperationexpressionevaluator.no_result; for (cacheoperationcontext context : contexts) { if (isconditionpassing(context, result)) { object key = generatekey(context, result); //獲取key cache.valuewrapper cached = findincaches(context, key); if (cached != null ) { return cached; } else { if (logger.istraceenabled()) { logger.trace( "no cache entry for key '" + key + "' in cache(s) " + context.getcachenames()); } } } } return null ; } //第三步:cacheaspectsupport.findincaches() //第四步:abstractcacheinvoker.doget() //第五步:abstractvalueadaptingcache.get(); @override public valuewrapper get(object key) { object value = lookup(key); return tovaluewrapper(value); } // 第六步:concurrentmapcache.lookup(); 從concurrentmap 中根據key獲取值 @override protected object lookup(object key) { return this .store.get(key); } |
三、cacheable 注解的幾個屬性:
1、cachenames/value:指定緩存組件的名字;將方法的返回結果放在哪個緩存中,是數組的方式,可以指定 多個緩存;
2、key:緩存數據使用的key;可以用它來指定。默認是使用方法參數的值 1-方法的返回值
? 編寫spel; #i d;參數id的值 #a0 #p0 #root.args[0]
? getemp[2]
3、keygenerator:key的生成器;可以自己指定key的生成器的組件id
? key/keygenerator:二選一使用;
4、cachemanager:指定緩存管理器;或者cacheresolver指定獲取解析器
5、condition:指定符合條件的情況下才緩存;
? ,condition = "#id>0"
? condition = "#a0>1":第一個參數的值》1的時候才進行緩存
6、unless:否定緩存;當unless指定的條件為true,方法的返回值就不會被緩存;可以獲取到結果進行判斷
? unless = "#result == null"
? unless = "#a0==2":如果第一個參數的值是2,結果不緩存;
7、sync:是否使用異步模式;異步模式的情況下unless不支持
四、cache使用:
1.cacheable的使用
1
2
3
4
5
6
|
@cacheable (value = { "emp" } /*,keygenerator = "mykeygenerator",condition = "#a0>1",unless = "#a0==2"*/ ) public employee getemp(integer id){ system.out.println( "查詢" +id+ "號員工" ); employee emp = employeemapper.getempbyid(id); return emp; } |
2.自定義keygenerator:
1
2
3
4
5
6
7
8
9
10
|
@bean ( "mykeygenerator" ) public keygenerator keygenerator(){ return new keygenerator(){ ? @override public object generate(object target, method method, object... params) { return method.getname()+ "[" + arrays.aslist(params).tostring()+ "]" ; } }; } |
3.cacheput的使用:更新緩存
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
/** * @cacheput:既調用方法,又更新緩存數據;同步更新緩存 * 修改了數據庫的某個數據,同時更新緩存; * 運行時機: * 1、先調用目標方法 * 2、將目標方法的結果緩存起來 * * 測試步驟: * 1、查詢1號員工;查到的結果會放在緩存中; * key:1 value:lastname:張三 * 2、以后查詢還是之前的結果 * 3、更新1號員工;【lastname:zhangsan;gender:0】 * 將方法的返回值也放進緩存了; * key:傳入的employee對象 值:返回的employee對象; * 4、查詢1號員工? * 應該是更新后的員工; * key = "#employee.id":使用傳入的參數的員工id; * key = "#result.id":使用返回后的id * @cacheable的key是不能用#result * 為什么是沒更新前的?【1號員工沒有在緩存中更新】 * */ @cacheput (value = "emp" ,key = "#result.id" ) public employee updateemp(employee employee){ system.out.println( "updateemp:" +employee); employeemapper.updateemp(employee); return employee; } |
4.cacheevict 緩存清除
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
/** * @cacheevict:緩存清除 * key:指定要清除的數據 * allentries = true:指定清除這個緩存中所有的數據 * beforeinvocation = false:緩存的清除是否在方法之前執行 * 默認代表緩存清除操作是在方法執行之后執行;如果出現異常緩存就不會清除 * * beforeinvocation = true: * 代表清除緩存操作是在方法運行之前執行,無論方法是否出現異常,緩存都清除 * * */ @cacheevict (value= "emp" ,beforeinvocation = true ,key = "#id" ) public void deleteemp(integer id){ system.out.println( "deleteemp:" +id); //employeemapper.deleteempbyid(id); int i = 10 / 0 ; } |
5.caching 復雜配置
1
2
3
4
5
6
7
8
9
10
11
12
13
|
// @caching 定義復雜的緩存規則 @caching ( cacheable = { @cacheable ( /*value="emp",*/key = "#lastname") }, put = { @cacheput(/*value="emp",*/key = "#result.id"), @cacheput(/*value="emp",*/ key = "#result.email" ) } ) public employee getempbylastname(string lastname){ return employeemapper.getempbylastname(lastname); } |
6.cacheconfig緩存清除
1
2
3
|
@cacheconfig (cachenames= "emp" ,cachemanager = "employeecachemanager" ) //抽取緩存的公共配置 @service public class employeeservice { |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/yangliuhbhd/article/details/80626468