Ehcache 与 SpringBoot 整合

tech2026-01-21  0

引入依赖 


SpringBoot 项目直接引入 spring-boot-starter-cache

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>

 有些还会专门引入 ehcache的依赖,其实没有必要,因为 spring-boot-starter-cache 已经依赖了 ehcache,会一并引入

<dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.10.4</version> </dependency>

 

<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false"> <diskStore path="c:\\ehcache"/> <cache name = "EhcacheDefaultCache" maxElementsInMemory = "20000" maxElementsOnDisk = "0" eternal = "false" overflowToDisk = "false" diskPersistent = "false" timeToIdleSeconds = "1800" timeToLiveSeconds = "1800" diskSpoolBufferSizeMB = "200" diskExpiryThreadIntervalSeconds = "10" memoryStoreEvictionPolicy = "FIFO" > <cacheEventListenerFactory class="com.seryo.cache.MyCacheEventListenerFactory"/> </cache> </ehcache>

diskStore

磁盘存储,将缓存中暂时不使用的对象,存储到磁盘,类似 Windows 虚拟内存。可以用绝对地址,也可以用相对地址。

 

defaultCache

默认缓存策略。如果没有特别说明,所有对象按照此配置项处理。

 

cache

自定义缓存策略。

name缓存名称默认值maxElementsInMemory缓存最大个数。 maxEntriesLocalHeap貌似新版用该属性代替了 maxElementsInMemory。 eternal缓存对象是否永久有效。设置之后 timeout 失效。falsetimeToIdleSeconds

缓存对象在失效前允许闲置的时间(单位:秒)。当 eternal 为 false 时生效。

如果为 0,表示可以无限期空闲。

0timeToLiveSeconds

缓存对象再失效前允许存活的时间(单位:秒)。当 eternal 为 false 时生效。

如果为 0,表示可以无限期存活。

0overflowToDisk

当内存中对象数量达到 maxElementsInMemory 时,Ehcache 是否将对象写到磁盘。

该属性已被 Strategy.LOCALTEMPSWAP 替换

 diskExpiryThreadIntervalSeconds磁盘失效线程运行时间间隔 

 

 

最新回复(0)