spring boot 中的快取使用

2021-09-09 06:54:22 字數 1328 閱讀 7306

借鑑:

專案中用到登入,對使用者的操作太多,所以將使用者的資訊通過快取的方式。

快取:ehcache 框架:spring boot

1.專案依賴

org.springframework.boot

spring-boot-starter-cache

net.sf.ehcache

ehcache

2.ehcache配置:定義快取的命名空間和基本引數

將快取配置放在resources/目錄下,spring boot 就會自定注入cachemanager物件。

@autowired

private cachemanager cachemanager ; // 可以注入cachemanager物件

<?xml version="1.0" encoding="utf-8"?>

3.開啟spring boot的快取使用

@enablecaching // 開啟快取

public class bootstrap }

4.使用

@cacheconfig(cachenames = )

public class userservice

@cacheevict(key="#loginid")

public void deletebyloginid(string loginid)

@cacheput(key="#user.loginid")

public user insert(user user)

@cacheput(key="#user.loginid")

public user update(user user)

}

第二中,注入cachemanager

@server

public class myserver

}

解釋:

1. @cacheconfig(cachenames = )  配置了該資料訪問物件中返回的內容將儲存於名為users的快取物件中,我們也可以不使用該註解,直接通過@cacheable自己配置快取集的名字來定義。
2. @cacheable()

加入快取:第一次執行該方法,會將指定的key和方法返回的結果加入快取。

查詢快取:當第二次執行,會首先在快取中查詢,沒有結果就執行並把加入快取,反正直接返回快取中資料。

引數解釋:

除了這裡用到的兩個註解之外,還有下面幾個核心註解:

springboot中Cache快取的使用

org.springframework.boot spring boot starter cache enablecaching public static void main string args cacheable 根據方法請求引數對其結果進行快取 查詢 自定義配置類配置keygenerato...

SpringBoot中Profile的使用(七)

檔案結構 1.先寫2個properties 2.模擬乙個實體類 data allargsconstructor public class datasource 3.編寫各自的config 其中 profile註解是標明該profile 側寫 的限定名 configuration propertyso...

Springboot中swagger的使用

需要匯入的依賴 io.springfoxgroupid springfox swagger2artifactid 2.7.0version dependency io.springfoxgroupid springfox swagger uiartifactid 2.7.0version depen...