前言
本次内容主要介绍基于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>
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); } }
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 应用程序缓存实现。文章内容重在缓存实现的基本步骤与方法,简化了具体的业务代码,有兴趣的朋友可以自行扩展。
最后
欢迎大家一起交流,喜欢文章记得点个赞哟,感谢支持!
- PDF怎么旋转页面,只需几步轻松搞定!
有时候我们下载一个PDF文件里面有页面是旋转的情况,用手机看的时候可以把手机旋转过来看,那么用电脑的时候总不可能也转过来看吧,笔记本是可以的台式的是不行的,这个时候我们就需要把PDF文件中旋转的页面转 ...
- Python高级特性: 12步轻松搞定Python装饰器
12步轻松搞定Python装饰器 通过 Python 装饰器实现DRY(不重复代码)原则: http://python.jobbole.com/84151/ 基本上一开始很难搞定python的装 ...
- 一文搞定Spring Boot + Vue 项目在Linux Mysql环境的部署(强烈建议收藏)
本文介绍Spring Boot.Vue .Vue Element编写的项目,在Linux下的部署,系统采用Mysql数据库.按照本文进行项目部署,不迷路. 1. 前言 典型的软件开发,经过" ...
- 三步轻松搞定delphi中CXGRID手动添加复表头(多行表头,报表头)
网上有代码动态生成cxgrid多行表头的源码,地址为:http://mycreature.blog.163.com/blog/static/556317200772524226400/ 如果要手动设计 ...
- 转载 12步轻松搞定python装饰器
作者: TypingQuietly 原文链接: https://www.jianshu.com/p/d68c6da1587a 呵呵!作为一名教python的老师,我发现学生们基本上一开始很难搞定pyt ...
- 12步轻松搞定Python装饰器
译者:寒寻 译文:http://www.cnblogs.com/imshome/p/8327438.html 原文:https://dzone.com/articles/understanding-p ...
- 一行配置搞定 Spring Boot项目的 log4j2 核弹漏洞!
相信昨天,很多小伙伴都因为Log4j2的史诗级漏洞忙翻了吧? 看到群里还有小伙伴说公司里还特别建了800+人的群在处理... 好在很快就有了缓解措施和解决方案.同时,log4j2官方也是速度影响发布了 ...
- 轻松搞定Spring+quartz的定时任务
1.spring 的定时任务写法有两种:一种是继承工作类,一种是普通的Bean,定时写法有两种写法:一种是以时间间隔启动任务SimpleTriggerBean,一种是以时刻启动任务CronTrigge ...
- java web每天定时执行任务(四步轻松搞定)
第一步: package com.eh.util; import java.util.Calendar; import java.util.Date; import java.util.Timer; ...
随机推荐
- 力扣(LeetCode)翻转字符串里的单词 个人题解
给定一个字符串,逐个翻转字符串中的每个单词. 示例 1: 输入: "the sky is blue" 输出: "blue is sky the" 示例 2: 输 ...
- 力扣(LeetCode)环形链表 个人题解
给定一个链表,判断链表中是否有环. 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始). 如果 pos 是 -1,则在该链表中没有环. 示例 1: 输入: ...
- 力扣(LeetCode)Excel表列名称 个人题解
给定一个正整数,返回它在 Excel 表中相对应的列名称. 例如, 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> ...
- CentOS 7安装图形界面步骤和问题解决方法
CentOS 7图形安装步骤: 首先需要进行必要的图形组件安装--命令为: yum groupinstall "X Window System " yum groupinstall ...
- 线程同步&线程池
线程同步&线程池 线程同步 线程不同步会出现的问题: 当多个线程操作同一资源时,会出现重复操作和和操作不存在的资源的问题,为了规避这一问题就需要线程的同步操作来实现资源的共同使用. 线程同步: ...
- Vmware EXSI服务迁移无法访问故障处理
Vmware EXSI服务迁移无法访问故障处理 我们在做微服务平台服务时经常在构建IAAS时,因为硬件资源的扩容.缩减等可维护性问题需要迁移或者复制方式扩容方式来快速扩建集群节点,提高微服务运营的可靠 ...
- Linux高级命令-sort、uniq、 cut、sed、grep、find、awk
sort(参考学习网站:http://www.cnblogs.com/dong008259/archive/2011/12/08/2281214.html) 功能:根据不同的数据类型进行排序 格式:s ...
- swiper实现一个好看的轮播图
轮播是我们在编写页面中经常遇到的模块,所以网上也会有各种有有关轮播图的插件.今天忽然间看到了swiper上一个高颜值的轮播功能,顺便做一下分享. 首先页面在head内要先引用 swiper的css 和 ...
- Apache和PHP结合、Apache默认虚拟主机
5月28日任务 课程内容: 11.14/11.15 Apache和PHP结合11.16/11.17 Apache默认虚拟主机 11.14/11.15 Apache和PHP结合 到目前为止虽然安装好了A ...
- 中标麒麟neokylin信息查看
中标麒麟Neokylin系统版本信息: # nkvers ############## NeoKylin Linux Version################# Release: NeoKyli ...