作者:谭朝红

地址: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依赖文件至少应该是下面的样子:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">   <modelVersion>4.0.0</modelVersion>  <parent>  <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.3.RELEASE</version>    <relativePath/> <!-- lookup parent from repository -->  </parent> <groupId>com.ramostear</groupId>    <artifactId>cache</artifactId>  <version>0.0.1-SNAPSHOT</version>   <name>cache</name>  <description>Demo project for Spring Boot</description> <properties>  <java.version>1.8</java.version>    </properties> <dependencies>    <dependency>  <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId>  </dependency> <dependency>  <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId>    </dependency> <dependency>  <groupId>org.ehcache</groupId>  <artifactId>ehcache</artifactId>    </dependency> <dependency>  <groupId>javax.cache</groupId>  <artifactId>cache-api</artifactId>  </dependency> <dependency>  <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId>   <scope>test</scope> </dependency> <dependency>  <groupId>org.projectlombok</groupId>    <artifactId>lombok</artifactId> </dependency> </dependencies>   <build>   <plugins> <plugin>  <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId>   </plugin> </plugins>    </build>
</project>

依赖说明:

  • 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应用程序缓存功能,你可以在应用主类中进行操作:

package com.ramostear.cache;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class CacheApplication { public static void main(String[] args) {    SpringApplication.run(CacheApplication.class, args);    }
}
接下来,需要创建一个 ehcache的配置文件,该文件放置在类路径下,如resources目录下:
<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">    <service> <jsr107:defaults enable-statistics="true"/>    </service>    <cache alias="person"> <key-type>java.lang.Long</key-type> <value-type>com.ramostear.cache.entity.Person</value-type>  <expiry>  <ttl unit="minutes">1</ttl>  </expiry> <listeners>   <listener>    <class>com.ramostear.cache.config.PersonCacheEventLogger</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>UPDATED</events-to-fire-on>  <events-to-fire-on>EXPIRED</events-to-fire-on>  <events-to-fire-on>REMOVED</events-to-fire-on>  <events-to-fire-on>EVICTED</events-to-fire-on>  </listener>   </listeners>  <resources>   <heap unit="entries">2000</heap> <offheap unit="MB">100</offheap> </resources>  </cache>
</config>

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

package com.ramostear.cache.config;
import org.ehcache.event.CacheEvent;
import org.ehcache.event.CacheEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** * @author ramostear    * @create-time 2019/4/7 0007-0:48  * @modify by : * @since:  */
public class PersonCacheEventLogger implements CacheEventListener<Object,Object>{ private static final Logger logger = LoggerFactory.getLogger(PersonCacheEventLogger.class);    @Override  public void onEvent(CacheEvent cacheEvent) {    logger.info("person caching event {} {} {} {}",   cacheEvent.getType(),   cacheEvent.getKey(),    cacheEvent.getOldValue(),   cacheEvent.getNewValue());  }
}

3. 使用@Cacheable注解

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

package com.ramostear.cache.service;
import com.ramostear.cache.entity.Person;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
/** * @author ramostear    * @create-time 2019/4/7 0007-0:51  * @modify by : * @since:  */
@Service(value = "personService")
public class PersonService {    @Cacheable(cacheNames = "person",key = "#id")    public Person getPerson(Long id){   Person person = new Person(id,"ramostear","ramostear@163.com");   return person;  }
}

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

4. 缓存测试

为了测试我们的应用程序,创建一个简单的Restful端点,它将调用PersonService返回一个Person对象:
package com.ramostear.cache.controller;
import com.ramostear.cache.entity.Person;
import com.ramostear.cache.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/** * @author ramostear    * @create-time 2019/4/7 0007-0:54  * @modify by : * @since:  */
@RestController
@RequestMapping("/persons")
public class PersonController { @Autowired private PersonService personService;    @GetMapping("/{id}") public ResponseEntity<Person> person(@PathVariable(value = "id") Long id){    return new ResponseEntity<>(personService.getPerson(id), HttpStatus.OK);  }
}
Person是一个简单的POJO类:
package com.ramostear.cache.entity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.io.Serializable;
/** * @author ramostear    * @create-time 2019/4/7 0007-0:45  * @modify by : * @since:  */
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Person implements Serializable{    private Long id;    private String username;    private String email;
}

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

{"id":1,"username":"ramostear","email":"ramostear@163.com"}

此时在观察控制台输出的日志信息:

2019-04-07 01:08:01.001  INFO 6704 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 5 ms
2019-04-07 01:08:01.054  INFO 6704 --- [e [_default_]-0] c.r.cache.config.PersonCacheEventLogger  : person caching event CREATED 1 null com.ramostear.cache.entity.Person@ba8a729
由于我们是第一次请求API,没有任何缓存数据。因此,Ehcache创建了一条缓存数据,可以通过CREATED看一了解到。
我们在ehcache.xml文件中将缓存过期时间设置成了1分钟(1),因此在一分钟之内我们刷新浏览器,不会看到有新的日志输出,一分钟之后,缓存过期,我们再次刷新浏览器,将看到如下的日志输出:
2019-04-07 01:09:28.612  INFO 6704 --- [e [_default_]-1] c.r.cache.config.PersonCacheEventLogger  : person caching event EXPIRED 1 com.ramostear.cache.entity.Person@a9f3c57 null
2019-04-07 01:09:28.612  INFO 6704 --- [e [_default_]-1] c.r.cache.config.PersonCacheEventLogger  : person caching event CREATED 1 null com.ramostear.cache.entity.Person@416900ce

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

结束语

在本次案例中,通过简单的三个步骤,讲解了基于 Ehcache 的 Spring Boot 应用程序缓存实现。
文章内容重在缓存实现的基本步骤与方法,简化了具体的业务代码,有兴趣的朋友可以自行扩展,期间遇到问题也可以随时与我联系。

正文结束

推荐阅读 ↓↓↓

1.

2.

3.

4.

5.

6.

7.

8.

一个人学习、工作很迷茫?

点击「阅读原文」加入我们的小圈子!

Spring Boot 集成 Ehcache 缓存,三步搞定!相关推荐

  1. spring boot集成ehcache 2.x 用于hibernate二级缓存

    spring boot集成ehcache 2x 用于hibernate二级缓存 项目依赖 Ehcache简介 hibernate二级缓存配置 ehcache配置文件 ehcache事件监听 注解方式使 ...

  2. Spring Boot集成Redis缓存之模拟高并发场景处理

    前言 同样我们以上一篇文章为例子,搭建好环境之后,我欧美可以模拟高并发场景下,我们的缓存效率怎么样,到底能不能解决我们实际项目中的缓存问题.也就是如何解决缓存穿透? Spring Boot集成Redi ...

  3. Spring Boot 集成 Redis 缓存

    Spring Boot 集成 Redis 缓存 在此章,我们将 SpringBoot 集成 Redis 缓存,Redis是一个开源的,基于内存的数据结构存储,可以用作数据库.缓存和消息代理,在本章仅讲 ...

  4. Flash Builder4.7极其简单破解方法-三步搞定(亲测)

    资讯类型: 转载 来源页面: http://weibo.com/2101024913/yvmR0D9Df 资讯原标题: 资讯原作者: 丿卓越丶星辰 翻译词数: 词 我的评论: 对这篇文你有啥看法,跟贴 ...

  5. android 图片墙拼贴,三步搞定 用APP打造图片文字拼贴效果

    相信大家一定见过一种文字拼贴效果的图片,许多大小不一.字体不同.颜色各异的文字拼合出一幅完整的画面.如果你曾经也想自己制作这么一张高端大气上档次的独特图片,却苦于自己的PS水平不到家,那么一定不要错过 ...

  6. linux 无法定位程序,三步搞定无法定位程序输入点 于动态链接库上

    三步搞定无法定位程序输入点 于动态链接库上 发布时间:2018-09-17 09:24 来源:互联网 当前栏目:电脑教程 上网的时候突然咚的一声弹出一个错误提示框,上边写着 iexplore.exe ...

  7. Flash Builder4.7极其简单破解方法-三步搞定

    Flash Builder4.7极其简单破解方法-三步搞定(亲测) 原方法适用于4.6版本,同样方法4.7完美破解,不敢独享 具体步骤如下: 1.到Adobe官网下载FlashBuilder 4.6, ...

  8. 漂亮的PPT模板:三步搞定年终报告

    漂亮的PPT模板:三步搞定年终报告 2013年年底悄然而至,有一个不得不做的难题,那就是如何做好年终报告?有没有想要吐槽的欲望,做完前要熬夜,做完后还被折磨.你是不是再也不想做PPT ,再也不会爱它了 ...

  9. caj文件怎么转换成pdf格式?三步搞定

    当我们需要查阅一些文献资料时,往往会遇到CAJ文件格式的问题.这种格式需要使用专业的阅读工具才能打开,让我们的阅读体验变得十分不便.为了解决这个问题,我们可以将CAJ文件转换成PDF文件格式.这样,无 ...

  10. Spring Boot集成Redis缓存之RedisTemplate的方式

    前言 Spring Boot 集成Redis,将自动配置 RedisTemplate,在需要使用的类中注入RedisTemplate的bean即可使用 @Autowired private Redis ...

最新文章

  1. web11 Struts处理表单数据
  2. 台式计算机装电源线,完美:[机箱电源线的连接方法]如何选择台式机电源?组装台式计算机机箱的电源线连接方法图...
  3. 优化查询、访问量大时的优化
  4. Spring Boot 与 Java 对应版本,以下表格由官方网站总结。
  5. 如何推送和播放RTMP H265流 (RTMP HEVC)
  6. OpenCV参考手册之Mat类详解
  7. 计算机网络---HTTP状态码
  8. 使用Docker Swarm来运行服务
  9. mysql5.7如何打开,mysql57怎么打开
  10. 2021年软考程序员考试大纲
  11. win10“无法完成操作,因为文件包含病毒或潜在的垃圾软件”解决办法
  12. 微信H5多级分佣开心刮刮乐源码
  13. 鼠标自动点击器linux,鼠标自动点击器PC版下载
  14. 计算机用几个字节储存,GB2312编码的字符在计算机中存储时使用几个字节
  15. Git查看本地配置信息
  16. Android的TextView中文字添加删除线,下划线
  17. T00LS MSF笔记
  18. mac如何在Finder中显示隐藏的文件或文件夹
  19. 功率放大芯片采用RFX2411 分集开关的2.4 GHz TX / RX增强器
  20. 开源项目eladmin--笔记

热门文章

  1. 《solidity学习笔记》chapter 2-solidity基础知识
  2. 《从零开始学Swift》学习笔记(Day 53)——do-try-catch错误处理模式
  3. linux命令笔记之ls
  4. 使用工具安装,运行,停止,卸载Window服务
  5. PacketiX ××× Server中三层交换机的路由表配置说明:
  6. js高级编号笔记[新]-事件
  7. 苹果Mac 3D 建模渲染软件:Vectorworks
  8. USB-C 端口在您的 Mac 上无法使用如何解决?
  9. 如何在Mac上恢复已删除或丢失的分区
  10. everything is nothing