springboot支持多種緩存框架,這裏我用到的是springboot默認支持的環境ehcache,ehcache小巧使用簡單,因此我在這裏介紹一下springboot如何集成ehcache。
1.pom.xml引入相關jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
2.創建ehcache.xml文件放到application.properties同目錄下即可
<ehcache
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<!—緩存路徑,用戶目錄下的base_ehcache目錄—>
<diskStore path="user.home/base_ehcache"/>
<defaultCache
maxElementsInMemory="20000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"/>
<!—緩存文件名:cache_user,同樣的可以配置多個緩存—>
<cache name="cache_user"
maxElementsInMemory="20000"
eternal="true"
overflowToDisk="true"
diskPersistent="false"
timeToLiveSeconds="0"
diskExpiryThreadIntervalSeconds="120"/>
<!— eternal:true表示對象永不過期,此時會忽略timeToIdleSeconds和timeToLiveSeconds屬性,默認爲false —>
<!— maxEntriesLocalHeap:堆內存中最大緩存對象數,0沒有限制 —>
<!— timeToIdleSeconds: 設定允許對象處於空閒狀態的最長時間,以秒爲單位。
當對象自從最近一次被訪問後,如果處於空閒狀態的時間超過了timeToIdleSeconds屬性值,這個對象就會過期,EHCache將把它從緩存中清空。
只有當eternal屬性爲false,該屬性纔有效。如果該屬性值爲0,則表示對象可以無限期地處於空閒狀態 —>
</ehcache>
3.加入application.properties配置
spring.cache.ehcache.config=classpath:/ehcache.xml
spring.cache.type=ehcache
4.使用
我用在service層中
@Service
@Transactional//事務
@CacheConfig(cacheNames = {"cache_user"})//緩存命名空間,存儲在哪個緩存中
public class SysManageService implements ISysManageService {
@Override
@CacheEvict(cacheNames = "cache_user",allEntries=true)
public void delSysConfig(String id) {
。。。
}
@Override
@CacheEvict(cacheNames = "cache_user",allEntries=true)
public void updateSysConfig(SysConfig sc) {
。。。
}
@Override
@Cacheable(cacheNames="cache_user",sync = true)
public SysConfig getSysConfigById(String id) {
。。。
}
}
簡單的介紹
1.@EnableCaching 啓用緩存配置
2.@Cacheable 指定某個方法的返回值是可以緩存的。在註解屬性中指定緩存規則。
參數:value、cacheNames:兩個等同的參數
key:#p0表示第一個參數(第一個參數是對象的話可以調用對象的屬性如#p0.id),或者用#+第一個參數名與#p0等同,要使用SpEL表達式#fx.id
condition:condition=”#name.length() < 32”
unless=”#result.hardback”
3.@Cacheput 將方法的返回值緩存到指定的key中;
例子:@CachePut(value=”cache_user”,key=”#p0.id”)//也可以用#object.id
4.@CacheEvict 刪除指定的緩存數據
參數:與@cacheable相同,多出2個參數:
allEntries:非必需,默認爲false。當爲true時,會移除所有數據
beforeInvocation:非必需,默認爲false,會在調用方法之後移除數據。當爲true時,會在調用
例子:@CacheEvict(cacheNames = “cache_user”,key=”#id” ,allEntries=true)
5.@Cacheable和@Cacheput都會將方法的執行結果按指定的key放到緩存中,
6.@Cacheable在執行時,會先檢測緩存中是否有數據存在,如果有,直接從緩存中讀取。如果沒有執行方法,將返回值放入緩存,而@Cacheput會先執行方法,然後再將執行結果寫入緩存。而使用@Cacheput的方法則一定會執行。
至此springboot2.0集成ehcache就完成了,使用緩存存儲常用的使用頻繁的查詢信息,可以提高效率,降低服務器與數據庫的壓力。