SpringBoot优雅的集成EhCache

发布于:2023-01-04 ⋅ 阅读:(198) ⋅ 点赞:(0)

最近在开发一个新项目,用的框架(中间件)比较多,所以最近的文章,都会以优雅的实战为主,也可以是框架(中间件)的简单DEMO。

今天给大家带来EhCache在SpringBoot框架下使用实战。

简介

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点。

注意概念中的关键词进程内,他传递了两个关键点:

  1. 速度快(进程内剔除了各种切换资源的损耗);
  2. 单机适用;

现在我们说缓存,迅速想到的绝对是我们的Redis,其实在Java生态下,有很多场景我们用EhCache更合理。

我这里简单的区分一下什么时候使用Redis,什么时候使用EhCache。

当我们的缓存需要多个进程(分布式)共享的时候,使用Redis,如果只是单机、单应用内的常见缓存,使用EhCache。

这篇文章不介绍太多的概念与配置,比较偏实战,老规矩,上导读图,直接进入实战环节。

 

优雅的集成EhCache

SpringBoot集成实战

创建项目

创建Maven项目

引入依赖

分别引入spring-boot-starter-web、spring-boot-starter-cache、cache-api、ehcache四个包

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
            <version>2.6.1</version></dependency>
        <dependency>
            <groupId>javax.cache</groupId>
            <artifactId>cache-api</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>3.8.1</version>
        </dependency>
    </dependencies>

记得刷新Maven引用

 

刷新Maven引用

配置启动类

配置启动类

指定配置

新建配置文件 application.properties 和 ehcache.xml

application.properties内容

ehcache.xml定义一个缓存模块,指定key和value的类型,指定过期时间。

<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">

    <cache alias="getUserInfo">
        <key-type>java.lang.String</key-type>
        <value-type>java.lang.String</value-type>
        <expiry>
            <ttl unit="seconds">30</ttl>
        </expiry>

        <resources>
            <heap unit="entries">2</heap>
            <offheap unit="MB">10</offheap>
        </resources>
    </cache>
</config>

增加配置注解config文件

通过配置注解开启EhCache

模拟场景

从控制器进入查找用户,查看是否多次调用Service的接口。

 整体代码结构

控制器入口 

service定义

场景测试

通过启动类,启动服务。

浏览器访问:http://localhost:8001/user/1

浏览器访问结果

第一次控制台输出:

之后刷新不会有变化,过了30s之后又会重新进入方法。

事件监听

在ehcache.xml增加监听配置

<listeners>
            <listener>
                <class>com.baeldung.cachetest.config.CacheEventLogger</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>EXPIRED</events-to-fire-on>
            </listener>
        </listeners>

测试监听

刷新浏览器测试

 

30秒之后刷新

注意有一个过期的事件。

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到