Redis之Spring常用註解整理

2021-08-27 11:07:31 字數 1250 閱讀 2772

redis 是乙個key-value 的儲存系統,value可以儲存string,list,map等各種型別的資料。多用於快取每次都要查詢的固定資料,降低對資料庫的訪問量,調高**效能。

下面主要介紹spring的三個關於redis的註解,@cacheable,@cacheevict,@cacheput。

@cacheable

@cacheable註解類似於儲存放法。註解可以標記在方法上,也可以在類上。在某乙個方法上就將這個方法的返回值放到cache中。在乙個類上,類中的方法的返回值都放到cache中。

@cacheable註解有幾個重要屬性。value 是快取的名稱。key鍵值對中的鍵,可以自定義也可以預設生成。condition是快取存入的條件。

//將地區名稱長度大於5的地區資訊,以地區名稱為key放入regions快取中 

@cacheable(value = " regions",key="#regionname",condition="#regionname.length()>10")

public listfindregion(string regionname)

@cacheevict

@cacheevict相當於刪除,將符合註解中屬性的快取清除。

//將regions快取資訊全刪除 

@cacheevict(value = "regions", allentries = true)

public void deleteregion() throws tpwsbusines***ception

@cacheevict除了value,key,condition 屬性外,還有 allentries、beforeinvocation屬性。allentries是boolean型別, 為true表示清除快取所有資料,預設為false。beforeinvocation預設為false,清除快取是發生在呼叫方法之後,改為true,就發上在呼叫方法之前,即使方法出錯也會清除。

@cacheput

@cacheput註解相當於update。確保新增註解的方法會執行,並將改變的資料寫入快取

// 執行查詢方法,並將更新regions快取的值 

@cacheput(value = " regions",)

public listupregion(string regionname)

參考:

spring學習筆記(7) spring常用註解

1 引入context命名空間 在spring的配置檔案中 配置檔案如下 xml 收藏 xmlns context org schema context org schema context spring context 2.5 xsd開啟配置 spring 會自動掃瞄cn.pic包下面有註解的類,...

spring 依賴注入之 Resource注入

public propertyvalues postprocessproperties propertyvalues pvs,object bean,string beanname catch throwable ex return pvs private injectionmetadata fin...

Spring中Responsebody註解的作用

好長一段時間以來都只是寫些測試 好久沒寫專案 了,以至於spring那套東西日漸生疏了。最近在折騰乙個小專案,寫了乙個controller用來響應ajax請求,結果斷點除錯發現一直返回 404 not response.折騰了快2小時,一直沒想到是註解的問題,萬般無賴之下上了度娘,方才如夢初醒,特意...