作者:谭朝红

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 应用程序缓存实现。

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

- END -

关注Java技术栈微信公众号,在后台回复关键字:boot,可以获取一份栈长整理的 Spring Boot 最新技术干货。

最近干货分享

公司不用 Spring Boot,果断离职了!

Java 12 骚操作, switch居然还能这样玩!

Java 12 骚操作, String居然还能这样玩

Spring Boot 1.x 正式退役,2.x大步向前

分享一份 2019 最新 Java 架构师学习资料

点击「阅读原文」加入栈长的战队~

Spring Boot 集成 Ehcache 缓存,三步搞定!的更多相关文章

  1. (37)Spring Boot集成EHCache实现缓存机制【从零开始学Spring Boot】

    [本文章是否对你有用以及是否有好的建议,请留言] 写后感:博主写这么一系列文章也不容易啊,请评论支持下. 如果看过我之前(35)的文章这一篇的文章就会很简单,没有什么挑战性了. 那么我们先说说这一篇文 ...

  2. iOS开发三步搞定百度推送

    iOS开发三步搞定百度推送   百度推送很简单,准备工作:在百度云推送平台注册应用,上传证书. 步骤一: 百度云推送平台 http://push.baidu.com/sdk/push_client_s ...

  3. Spring Boot集成EHCache实现缓存机制

    SpringBoot 缓存(EhCache 2.x 篇) SpringBoot 缓存 在 Spring Boot中,通过@EnableCaching注解自动化配置合适的缓存管理器(CacheManag ...

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

    https://www.jianshu.com/p/87b2c309b776 本文将介绍如何在spring boot中集成ehcache作为hibernate的二级缓存.各个框架版本如下 spring ...

  5. spring boot集成redis缓存

    spring boot项目中使用redis作为缓存. 先创建spring boot的maven工程,在pom.xml中添加依赖 <dependency> <groupId>or ...

  6. Spring Boot Starter自定义实现三步曲

    实现自定义的spring boot starter,只需要三步: 1.一个Bean 2.一个自动配置类 3.一个META-INF/spring.factories配置文件 下面用代码演示这三步. 项目 ...

  7. 详解Spring MVC 集成EHCache缓存_java - JAVA

    文章来源:嗨学网 敏而好学论坛www.piaodoo.com 欢迎大家相互学习 废话少说,直接上代码: ehcache.xml 文件 <?xml version="1.0" ...

  8. 三步搞定IDEA集成热部署

    第一步.在你的SpringBoot项目中添加DevTools依赖 <!-- 热部署DevTools --> <dependency> <groupId>org.sp ...

  9. Excel大数据排查重复行内容方法,三步搞定!

    首先第一步,我们找到一个空白列D输入公式“=A1&B1&C1”: 然后第二步,再选择下一空白列输入公式“=IF(COUNTIF(D:D,D1)>1,"重复", ...

随机推荐

  1. VMmare下安装redhat

    一.虚拟机必须安装在自定义的文件夹下,虚拟硬盘文件必须存放在自定义路径下(避免中文) 二.安装时选择linux类型时必须选择red hat enterprise linux 5 64位 三.操作系统名 ...

  2. NOIP模拟赛(by hzwer) T2 小奇的序列

    [题目背景] 小奇总是在数学课上思考奇怪的问题. [问题描述] 给定一个长度为 n 的数列,以及 m 次询问,每次给出三个数 l,r 和 P, 询问 (a[l'] + a[l'+1] + ... + ...

  3. springboot日期转换器

    注:该功能并非springboot特有的功能,springmvc同样具有         一.使用方法     创建一个DateConverter类实现Converter接口 注:importorg. ...

  4. linux运维、架构之路-MySQL备份与恢复(四)

    一.备份方式 ①逻辑备份(文件表示:SQL语句) ②物理备份(数据文件的二进制副本) ③基于快照的备份 ④基于复制的备份 二.备份工具 ①mysqldump:原生自带的逻辑备份工具 ②mysqlbin ...

  5. echart-折线图,数据太多想变成鼠标拖动和滚动的效果?以及数据的默认圈圈如何自定义圆圈的样式

    1.数据太多怎么办???想拖拽,想滑动 dataZoom: [ { type: 'slider', } ] dataZoom: [ { type: 'inside',  }] 两种功能都需要,还想调样 ...

  6. Shell入门02

    Shell入门-02 1.重定向 标准输入(<) 标准输出 标准错误重回定向 程序 = 指令 + 数据 命令   变量 在程序中,数据如何输入?又如何输出? 数据输入:键盘 – 标准输入,但是并 ...

  7. Ubuntu 14.04 DNS 丢失 | 中文输入法配置 (转载)

    1)彻底解决Ubuntu 14.04 重启后DNS配置丢失的问题: http://www.tuicool.com/articles/RVZn2y 2)Ubuntu 14.04中文输入法的安装   ht ...

  8. Python学习笔记(二)Sublime Text 3 安装Package Control

    原来Subl3安装Package Control很麻烦,现在简单的方法来了 一.简单的安装方法 使用Ctrl+`快捷键或者通过View->Show Console菜单打开命令行,粘贴如下代码: ...

  9. python3下multiprocessing、threading和gevent性能对比----暨进程池、线程池和协程池性能对比

    python3下multiprocessing.threading和gevent性能对比----暨进程池.线程池和协程池性能对比   标签: python3 / 线程池 / multiprocessi ...

  10. easyui表格适应bootstrap

    .panel1 { overflow: hidden; text-align: left; margin:; border:; -moz-border-radius: 0 0 0 0; -webkit ...