hystrix支持將一個請求結果緩存起來,下一個具有相同key的請求將直接從緩存中取出結果,減少請求開銷。要使用該功能必須管理hystrixrequestcontext,如果請求b要用到請求a的結果緩存,a和b必須同處一個context。通過hystrixrequestcontext.initializecontext()和context.shutdown()可以構建一個context,這兩條語句間的所有請求都處于同一個context,當然這個管理過程可以通過自定義的filter來實現,參考上一篇文章 http://www.jfrwli.cn/article/160600.html
hystrix請求緩存注解
@cacheresult 加入該注解的方法將開啟請求緩存,默認情況下該方法的所有參數作為緩存的key,也就是說只有該方法的所有參數都一致時才會走緩存。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
@service public class usercacheservice { @autowired private userfeignclient userfeignclient; /** * @hystrixcommand 的requestcache.enabled 可控制是否支持緩存 * 只有加了@cacheresult才能緩存,即使requestcache.enabled=true * @param id 用戶id * @return 指定的用戶 */ @cacheresult @hystrixcommand (commandproperties = { @hystrixproperty (name= "requestcache.enabled" ,value = "true" ) }) public user finduserbyid(integer id){ return userfeignclient.finduserbyid(id); } } |
如果requestcache.enabled設置為false,即使加了@cacheresult,緩存也不起作用。
@cachekey 通過該注解可以指定緩存的key
1
2
3
4
5
6
7
|
@cacheresult @hystrixcommand (commandproperties = { @hystrixproperty (name= "requestcache.enabled" ,value = "true" ) }) public user finduserbyidandname( @cachekey integer id,string name){ return userfeignclient.finduserbyid(id); } |
上面的代碼我們用@cachekey修飾了id字段,說明只要id相同的請求默認都會走緩存,與name字段無關,如果我們指定了@cacheresult的cachekeymethod屬性,則@cachekey注解無效
@cacheremove 該注解的作用就是使緩存失效
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
/** * 通過@cacheremove 注解指定當調用finduserbyid時將此方法的緩存刪除 * @param id 用戶id * @param name 用戶姓名 * @return 指定的用戶 */ @cacheresult @cacheremove (commandkey = "finduserbyid" ) @hystrixcommand (commandproperties = { @hystrixproperty (name= "requestcache.enabled" ,value = "true" ) }) public user finduserbyidandname2( @cachekey integer id,string name){ return userfeignclient.finduserbyid(id); } |
以上代碼指定了@cacheremove的屬性commandkey的值為finduserbyid,作用就是當調用finduserbyid時,此方法的緩存將刪除。
完整版代碼請參考:https://github.com/jingangwang/micro-service
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/heartroll/article/details/78910509