大家好,我是连边。
今天给大家带来EhCache
在SpringBoot
框架下使用实战。
简介
EhCache
是一个纯Java的进程内
缓存框架,具有快速、精干等特点。
注意概念中的关键词进程内
,他传递了两个关键点
:
- 速度快(进程内剔除了各种切换资源的损耗);
- 单机适用;
现在我们说缓存,迅速想到的绝对是我们的Redis
,其实在Java生态下,有很多场景我们用EhCache
更合理。
我这里简单的区分一下什么时候使用Redis
,什么时候使用EhCache
。
当我们的缓存需要多个进程(分布式)共享的时候,使用Redis
,如果只是单机、单应用内的常见缓存,使用EhCache
。
这篇文章不介绍太多的概念与配置,比较偏实战,老规矩,上导读图,直接进入实战环节。

SpringBoot集成实战
创建项目

引入依赖
分别引入spring-boot-starter-web、spring-boot-starter-cache、cache-api、ehcache四个包
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> <version>2.6.1</version></dependency> <dependency> <groupId>javax.cache</groupId> <artifactId>cache-api</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> <version>3.8.1</version> </dependency> </dependencies>
|
记得刷新Maven引用

配置启动类

指定配置
新建配置文件 application.properties
和 ehcache.xml

ehcache.xml定义一个缓存模块,指定key和value的类型,指定过期时间。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.ehcache.org/v3" xmlns:jsr107="http://www.ehcache.org/v3/jsr107" xsi:schemaLocation=" http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">
<cache alias="getUserInfo"> <key-type>java.lang.String</key-type> <value-type>java.lang.String</value-type> <expiry> <ttl unit="seconds">30</ttl> </expiry>
<resources> <heap unit="entries">2</heap> <offheap unit="MB">10</offheap> </resources> </cache> </config>
|
增加配置注解config文件

模拟场景
从控制器进入查找用户,查看是否多次调用Service
的接口。



场景测试
通过启动类,启动服务。
浏览器访问:http://localhost:8001/user/1

第一次控制台输出:

之后刷新不会有变化,过了30s之后又会重新进入方法。
事件监听
在ehcache.xml
增加监听配置
1 2 3 4 5 6 7 8 9
| <listeners> <listener> <class>com.baeldung.cachetest.config.CacheEventLogger</class> <event-firing-mode>ASYNCHRONOUS</event-firing-mode> <event-ordering-mode>UNORDERED</event-ordering-mode> <events-to-fire-on>CREATED</events-to-fire-on> <events-to-fire-on>EXPIRED</events-to-fire-on> </listener> </listeners>
|
测试监听
刷新浏览器测试


注意有一个过期的事件。
源代码地址
好了,EhCache
简单的实战就到这里结束了,源码可以从 https://github.com/lianbian/EhCache 查看,微信公众号读者可以点击阅读原文。
我是连边,专注于Java和架构领域,坚持撰写有原理,有实战,有体系的技术文章。
关注 订阅号@连边
不错过精彩文章
