Spring Boot-Ehcache 3.0实现本地缓存

作者:: 谭朝红

原文: ramostear.com

本次内容主要介绍基于 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 的缓存规范

  1. 配置 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());
    }
}

  1. 使用 @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 的缓存功能。接下来,我们将测试一下缓存的实际情况。

  1. 缓存测试

为了测试我们的应用程序,创建一个简单的 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 应用程序缓存实现。文章内容重在缓存实现的基本步骤与方法,简化了具体的业务代码,有兴趣的朋友可以自行扩展,期间遇到问题也可以随时与我联系。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 Ehcache 缓存来配置 Spring Boot 的步骤如下: 1. 添加 Ehcache 依赖:在 pom.xml 文件中添加 Ehcache 的相关依赖。 ```xml <dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> ``` 2. 创建 Ehcache 配置文件:在 src/main/resources 目录下创建一个 ehcache.xml 文件,并配置缓存的名称、容量、过期时间等信息。 ```xml <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.ehcache.org/v3" xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd"> <cache alias="myCache"> <expiry> <ttl unit="seconds">60</ttl> </expiry> <heap unit="entries">100</heap> </cache> </config> ``` 3. 配置 Spring Boot 应用程序:在 Spring Boot 的配置类上使用 @EnableCaching 注解开启缓存功能,并指定 Ehcache缓存管理器。 ```java import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.ehcache.EhCacheCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @EnableCaching public class CacheConfig { @Bean public EhCacheCacheManager cacheManager(CacheManager ehCacheManager) { return new EhCacheCacheManager(ehCacheManager); } } ``` 4. 使用缓存注解:在需要缓存的方法上使用 Spring缓存注解,比如 @Cacheable、@CachePut、@CacheEvict 等。 ```java @Service public class MyService { @Cacheable("myCache") public String getCachedData(String key) { // 从数据库或其他数据源中获取数据 return data; } } ``` 以上是使用 Ehcache 缓存配置 Spring Boot 的基本步骤。请根据你的具体需求进行相应的修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值