Spring Boot 集成 Ehcache 缓存,三步搞定

来源:www.ramostear.com/articles/spring_boot_ehcache.html

本次内容主要介绍基于Ehcache 3.0来快速实现Spring Boot应用程序的数据缓存功能。在Spring Boot应用程序中,我们可以通过Spring Caching来快速搞定数据缓存。

接下来我们将介绍如何在三步之内搞定 Spring Boot 缓存。

1. 创建一个Spring Boot工程

你所创建的Spring Boot应用程序的maven依赖文件至少应该是下面的样子:

Spring Boot 集成 Ehcache 缓存,三步搞定

Spring Boot 集成 Ehcache 缓存,三步搞定

Spring Boot 集成 Ehcache 缓存,三步搞定

依赖说明:

spring-boot-starter-cache为Spring Boot应用程序提供缓存支持

ehcache提供了Ehcache的缓存实现

cache-api 提供了基于JSR-107的缓存规范

2. 配置Ehcache缓存

现在,需要告诉Spring Boot去哪里找缓存配置文件,这需要在Spring Boot配置文件中进行设置:

spring.cache.jcache.config=classpath:ehcache.xml

然后使用@EnableCaching注解开启Spring Boot应用程序缓存功能,你可以在应用主类中进行操作:

Spring Boot 集成 Ehcache 缓存,三步搞定

接下来,需要创建一个 ehcache 的配置文件,该文件放置在类路径下,如resources目录下:

Spring Boot 集成 Ehcache 缓存,三步搞定

Spring Boot 集成 Ehcache 缓存,三步搞定

最后,还需要定义个缓存事件监听器,用于记录系统操作缓存数据的情况,最快的方法是实现CacheEventListener接口:

Spring Boot 集成 Ehcache 缓存,三步搞定

3. 使用@Cacheable注解

要让Spring Boot能够缓存我们的数据,还需要使用@Cacheable注解对业务方法进行注释,告诉Spring Boot该方法中产生的数据需要加入到缓存中:

Spring Boot 集成 Ehcache 缓存,三步搞定

通过以上三个步骤,我们就完成了Spring Boot的缓存功能。接下来,我们将测试一下缓存的实际情况。

4. 缓存测试

为了测试我们的应用程序,创建一个简单的Restful端点,它将调用PersonService返回一个Person对象:

Spring Boot 集成 Ehcache 缓存,三步搞定

Person是一个简单的POJO类:

Spring Boot 集成 Ehcache 缓存,三步搞定

以上准备工作都完成后,让我们编译并运行应用程序。项目成功启动后,使用浏览器打开:http://localhost:8080/persons/1 ,你将在浏览器页面中看到如下的信息:

Spring Boot 集成 Ehcache 缓存,三步搞定

由于我们是第一次请求API,没有任何缓存数据。因此,Ehcache创建了一条缓存数据,可以通过CREATED看一了解到。

我们在ehcache.xml文件中将缓存过期时间设置成了1分钟(1),因此在一分钟之内我们刷新浏览器,不会看到有新的日志输出,一分钟之后,缓存过期,我们再次刷新浏览器,将看到如下的日志输出:

Spring Boot 集成 Ehcache 缓存,三步搞定

第一条日志提示缓存已经过期,第二条日志提示Ehcache重新创建了一条缓存数据。

结束语

在本次案例中,通过简单的三个步骤,讲解了基于 Ehcache 的 Spring Boot 应用程序缓存实现。

文章内容重在缓存实现的基本步骤与方法,简化了具体的业务代码,有兴趣的朋友可以自行扩展,期间遇到问题也可以随时与我联系。


分享到:


相關文章: