使用ehcache三步搞定springboot缓存的方法示例
作者:罗摩尔 发布时间:2021-06-25 04:44:12
本次内容主要介绍基于Ehcache 3.0来快速实现Spring Boot应用程序的数据缓存功能。在Spring Boot应用程序中,我们可以通过Spring Caching来快速搞定数据缓存。接下来我们将介绍如何在三步之内搞定Spring Boot缓存。
1. 创建一个Spring Boot工程并添加Maven依赖
你所创建的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应用程序缓存实现。文章内容重在缓存实现的基本步骤与方法,简化了具体的业务代码,有兴趣的朋友可以自行扩展,期间遇到问题也可以随时与我联系。
来源:https://juejin.im/post/5ca8e8516fb9a05e3b24c01b
猜你喜欢
- @PathVariable和@RequestParam传参为空@RestControllerpublic class UserControl
- 开篇:我们将前面的springboot整合H2内存数据库,实现单元测试与数据库无关性提供的Restful服务注册到spring cloud的
- 一个非侵入的api编译、收集、Rest文档生成工具。工具通过分析代码和注释,获取文档信息,生成RestDoc文档前言程序员一直以来都有一个烦
- thinking in java3中的多态People are often confused by other, non-object-or
- 前言请看下面几个问题Spring为什么不推荐使用@Autowired 注解?为什么推荐使用@Resource 代替&nb
- 循环结构分两大类,一类是当型,一类是直到型。当型:当布尔值表达式条件为True时,反复执行某语句,当布尔表达式的值为False时才停止循环,
- 官方文档 8.0Spring为不同缓存做了一层抽象,这里通过阅读文档以及源码会对使用以及原理做一些学习笔记。1.简介
- 建造者模式针对的是复杂对象的构建,比如一个产品有多个部分构成,每个部分都可以单独进行生产,这时候就可以用建造者模式,由Builder构造产品
- 目录前言connectTimeout:callTimeout:pingIntervalwriteTimeoutreadTimeout总结前言
- 前言在上一篇文章中讲完了SpringMVC的大部分知识,此篇文章中主要讲解 * 。上一篇文章🚩 * 的使用是非常普遍的。例如在 OA系统中通
- 概念优先级队列是一种先进先出(FIFO)的数据结构,与队列不同的是,操作的数据带有优先级,通俗的讲就是可以比较大小,在出队列的时候往往需要优
- 前言xxljob 是采用 java 开发的开源的任务调度系统,架构上分为调度管理器、执行器,目前除了官方提供的 java 执行器外,也有 g
- Spring boot默认使用的是SimpleCacheConfiguration,即使用ConcurrentMapCacheManager
- 使用Mybatis-Plus的SqlSessionFactory问题前些日子工作中出现一个问题,项目中使用了MybatisPlus,然后出现
- 1.Thread的构造方法package threadAPI;public class CreateThread { publi
- 本文实例讲述了Java实现的计算最大下标距离算法。分享给大家供大家参考,具体如下:题目描述给定一个整形数组,找出最大下标距离j−i, 当且A
- 直接用idea clean install 进行打包maven项目时,如果没有进行设置会把测试文件也打包进去。想要忽略test文件将Mave
- 本文实例讲述了Spring实战之协调作用域不同步的Bean操作。分享给大家供大家参考,具体如下:一 配置<?xml version=&
- 问题描述:因为领导的一个需求,需要用到使用resultMap,很久没使用了,结果就除了点意外。就记录下这个问题准备两个类:author(作者
- 本文实例讲述了C#中数组初始化与数组元素复制的方法。分享给大家供大家参考。具体如下:下面的代码演示如何创建和初始化数组,以及C#中如何将数组