一、創建項目並導入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.6</version>
</dependency>
二、相關配置和代碼
ehcache.xml模板
<ehcacheupdateCheck="false"dynamicConfig="false">
<!--表示當前系統臨時目錄-->
<diskStorepath="java.io.tmpdir/ehcache"/>
<!--
name:緩存名稱。
maxElementsInMemory:緩存最大個數。
eternal:對象是否永久有效,一但設置了,timeout將不起作用。
timeToIdleSeconds:設置對象在失效前的允許閑置時間(單位:秒)。僅當eternal=false對象不是永久有效時使用,可選屬性,默認值是0,也就是可閑置時間無窮大。
timeToLiveSeconds:設置對象在失效前允許存活時間(單位:秒)。最大時間介於創建時間和失效時間之間。僅當eternal=false對象不是永久有效時使用,默認是0.,也就是對象存活時間無窮大。
overflowToDisk:當內存中對象數量達到maxElementsInMemory時,Ehcache將會對象寫到磁盤中。
diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每個Cache都應該有自己的一個緩沖區。
maxElementsOnDisk:硬盤最大緩存個數。
diskPersistent:是否緩存虛擬機重啟期數據WhetherthediskstorepersistsbetweenrestartsoftheVirtualMachine.Thedefaultvalueisfalse.
diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒。
memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你可以設置為FIFO(先進先出)或是LFU(較少使用)。
clearOnFlush:內存數量最大時是否清除。
-->
<defaultCachename="defaultCache"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
maxElementsOnDisk="100000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"/>
<cachename="myehcache"
maxEntriesLocalHeap="1000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="600"/>
</ehcache>
復制上面代碼到
這樣ehcache模板就創建好了
創建好模板就需要在resource下創建一個ehcache的xml文件
這個文件可以自定義名字和使用ehcache作為文件名
如果是xxx.xml就需要在application.properites指定文件了
spring.cache.ehcache.config=classpath:你的文件名.xml
如果使用ehcache.xml就不要在application.properites里面寫配置了
下面代碼和SpringCache整合redis一模一樣
https://www.cnblogs.com/fernfei/p/12174174.html
注:springcache只是制定規范,具體實現是redis或ehcache 就好比jdbc用哪個數據庫直接更換數據庫驅動就可以了