SpringBoot优雅的集成EhCache

大家好,我是连边。

今天给大家带来EhCacheSpringBoot框架下使用实战。

简介

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点。

注意概念中的关键词进程内,他传递了两个关键点

  1. 速度快(进程内剔除了各种切换资源的损耗);
  2. 单机适用;

现在我们说缓存,迅速想到的绝对是我们的Redis,其实在Java生态下,有很多场景我们用EhCache更合理。

我这里简单的区分一下什么时候使用Redis,什么时候使用EhCache

当我们的缓存需要多个进程(分布式)共享的时候,使用Redis,如果只是单机、单应用内的常见缓存,使用EhCache

这篇文章不介绍太多的概念与配置,比较偏实战,老规矩,上导读图,直接进入实战环节。

优雅的集成EhCache

SpringBoot集成实战

创建项目

创建Maven项目

引入依赖

分别引入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引用

刷新Maven引用

配置启动类

配置启动类

指定配置

新建配置文件 application.propertiesehcache.xml

application.properties内容

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文件

通过配置注解开启EhCache

模拟场景

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

整体代码结构

控制器入口

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>

测试监听

刷新浏览器测试

第一次访问

30秒之后刷新

注意有一个过期的事件。

源代码地址

好了,EhCache简单的实战就到这里结束了,源码可以从 https://github.com/lianbian/EhCache 查看,微信公众号读者可以点击阅读原文。

我是连边,专注于Java和架构领域,坚持撰写有原理,有实战,有体系的技术文章。

关注 订阅号@连边 不错过精彩文章

订阅号@连边


SpringBoot优雅的集成EhCache
https://www.lianbian.net/java/ad129d13f02b.html
作者
连边
发布于
2022年3月15日
许可协议