Springboot 整合 Ehcache3 详细步骤
最近想在Springboot 项目中整合 Ehcache3 缓存,我们讲下详细配置整合步骤。首先说下版本,我这里是使用的springboot 2.6.6版本,选择的Ehcache3 是3.10.8版本。
第一步:导入maven依赖
maven依赖需要有三个,配置如下:
<!-- 引入Spring Boot缓存依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> <version>2.6.6</version> </dependency> <!-- 引入EhCache缓存库依赖 --> <dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> <version>3.10.8</version> </dependency> <dependency> <groupId>javax.cache</groupId> <artifactId>cache-api</artifactId> <version>1.1.1</version> </dependency>
第二步:配置ehcache.xml
我这里使用的是xml配置方式,当然你也可以选择@Configuration
代码配置方式,个人觉得还是xml配置方式更加清晰明了。
在resources目录下新增ehcache.xml,具体配置如下:
<?xml version="1.0" encoding="UTF-8"?> <config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='http://www.ehcache.org/v3' xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core.xsd"> <!-- 指定硬盘存储目录,如用不到硬盘缓存,无需设置 --> <persistence directory="./ehcacheData" /> <!-- cache-template 创建公开配置,被继承用 --> <cache-template name="myDefaults"> <key-type>java.lang.Long</key-type> <value-type>java.lang.String</value-type> <heap unit="entries">200</heap> </cache-template> <!-- 继承自myDefaults,并重写其参数 这里是一个demo --> <cache alias="demo" uses-template="myDefaults"> <key-type>java.lang.String</key-type> <expiry> <!--此处会覆盖模版中的(TTL)配置 --> <ttl unit="days">90</ttl> </expiry> <resources> <heap unit="entries">2000</heap> <offheap unit="MB">100</offheap> </resources> </cache> </config>
更多配置参数请参考官网:https://www.ehcache.org/documentation/
第三步:配置application.yaml
这里需要注意ehcache3和ehcache2版本配置不一样,这是我们使用的是jcache
,而不是ehcache
,在application.yaml
中新增配置如下:
spring: cache: type: jcache jcache: config: classpath:ehcache.xml
第四步:启用缓存
我们需要在Application.java
程序启动入口文件上新增启用ehcache缓存的注解,如下:
@EnableCaching
至此,springboot已经整合好了ehcache3了,接下来就是使用了,只需要结合Spring中@Cacheable
注解即可使用,以下是类似代码:
@Cacheable(cacheNames = "demo", key = "#province") public String findPostcodeByRegion(String province) { // 省略 }
注意这里的cacheNames
要和ehcache.xml
中配置保持一致,否则会找不到该缓存。
@Cacheable
注解更详细的用法请参考文章: