评论

收藏

[Java] 使用ehcache三步搞定springboot缓存的方法示例

编程语言 编程语言 发布于:2021-08-17 12:27 | 阅读数:416 | 评论:0

本次内容主要介绍基于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应用程序缓存实现。文章内容重在缓存实现的基本步骤与方法,简化了具体的业务代码,有兴趣的朋友可以自行扩展,期间遇到问题也可以随时与我联系。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持CodeAE代码之家
原文链接:https://juejin.im/post/5ca8e8516fb9a05e3b24c01b

关注下面的标签,发现更多相似文章