Spring Boot 集成 Ehcache 緩存,三步搞定狡赐!

本次內(nèi)容主要介紹基于Ehcache 3.0來(lái)快速實(shí)現(xiàn)Spring Boot應(yīng)用程序的數(shù)據(jù)緩存功能窑业。在Spring Boot應(yīng)用程序中,我們可以通過(guò)Spring Caching來(lái)快速搞定數(shù)據(jù)緩存枕屉。

接下來(lái)我們將介紹如何在三步之內(nèi)搞定 Spring Boot 緩存常柄。

1. 創(chuàng)建一個(gè)Spring Boot工程

你所創(chuàng)建的Spring Boot應(yīng)用程序的maven依賴(lài)文件至少應(yīng)該是下面的樣子:

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

依賴(lài)說(shuō)明:

  • spring-boot-starter-cache為Spring Boot應(yīng)用程序提供緩存支持
  • ehcache提供了Ehcache的緩存實(shí)現(xiàn)
  • cache-api 提供了基于JSR-107的緩存規(guī)范

2. 配置Ehcache緩存

現(xiàn)在,需要告訴Spring Boot去哪里找緩存配置文件搀擂,這需要在Spring Boot配置文件中進(jìn)行設(shè)置:

spring.cache.jcache.config=classpath:ehcache.xml

然后使用@EnableCaching注解開(kāi)啟Spring Boot應(yīng)用程序緩存功能西潘,你可以在應(yīng)用主類(lèi)中進(jìn)行操作:

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);
    }
}

接下來(lái),需要?jiǎng)?chuàng)建一個(gè) ehcache 的配置文件哨颂,該文件放置在類(lèi)路徑下喷市,如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>

最后,還需要定義個(gè)緩存事件監(jiān)聽(tīng)器威恼,用于記錄系統(tǒng)操作緩存數(shù)據(jù)的情況品姓,最快的方法是實(shí)現(xiàn)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能夠緩存我們的數(shù)據(jù),還需要使用@Cacheable注解對(duì)業(yè)務(wù)方法進(jìn)行注釋?zhuān)嬖VSpring Boot該方法中產(chǎn)生的數(shù)據(jù)需要加入到緩存中:

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;
    }
}

通過(guò)以上三個(gè)步驟箫措,我們就完成了Spring Boot的緩存功能腹备。接下來(lái),我們將測(cè)試一下緩存的實(shí)際情況蒂破。

4. 緩存測(cè)試

為了測(cè)試我們的應(yīng)用程序馏谨,創(chuàng)建一個(gè)簡(jiǎn)單的Restful端點(diǎn),它將調(diào)用PersonService返回一個(gè)Person對(duì)象:

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是一個(gè)簡(jiǎn)單的POJO類(lèi):

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;
}

以上準(zhǔn)備工作都完成后附迷,讓我們編譯并運(yùn)行應(yīng)用程序惧互。項(xiàng)目成功啟動(dòng)后,使用瀏覽器打開(kāi):http://localhost:8080/persons/1 ,你將在瀏覽器頁(yè)面中看到如下的信息:

{"id":1,"username":"ramostear","email":"ramostear@163.com"}

此時(shí)在觀察控制臺(tái)輸出的日志信息:

1. 2019-04-07 01:08:01.001  INFO 6704 --- [nio-8080-exec-1] 
o.s.web.servlet.DispatcherServlet        : Completed 
initialization in 5 ms
2. 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

由于我們是第一次請(qǐng)求API喇伯,沒(méi)有任何緩存數(shù)據(jù)喊儡。因此,Ehcache創(chuàng)建了一條緩存數(shù)據(jù)稻据,可以通過(guò)CREATED看一了解到艾猜。

我們?cè)趀hcache.xml文件中將緩存過(guò)期時(shí)間設(shè)置成了1分鐘(1),因此在一分鐘之內(nèi)我們刷新瀏覽器捻悯,不會(huì)看到有新的日志輸出匆赃,一分鐘之后,緩存過(guò)期今缚,我們?cè)俅嗡⑿聻g覽器算柳,將看到如下的日志輸出:

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
2. 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

第一條日志提示緩存已經(jīng)過(guò)期,第二條日志提示Ehcache重新創(chuàng)建了一條緩存數(shù)據(jù)姓言。

結(jié)束語(yǔ)

在本次案例中瞬项,通過(guò)簡(jiǎn)單的三個(gè)步驟蔗蹋,講解了基于 Ehcache 的 Spring Boot 應(yīng)用程序緩存實(shí)現(xiàn)。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末囱淋,一起剝皮案震驚了整個(gè)濱河市猪杭,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌妥衣,老刑警劉巖皂吮,帶你破解...
    沈念sama閱讀 219,039評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異称鳞,居然都是意外死亡涮较,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)冈止,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人候齿,你說(shuō)我怎么就攤上這事熙暴。” “怎么了慌盯?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,417評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵周霉,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我亚皂,道長(zhǎng)俱箱,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,868評(píng)論 1 295
  • 正文 為了忘掉前任灭必,我火速辦了婚禮狞谱,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘禁漓。我一直安慰自己跟衅,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,892評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布播歼。 她就那樣靜靜地躺著伶跷,像睡著了一般。 火紅的嫁衣襯著肌膚如雪秘狞。 梳的紋絲不亂的頭發(fā)上叭莫,一...
    開(kāi)封第一講書(shū)人閱讀 51,692評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音烁试,去河邊找鬼雇初。 笑死,一個(gè)胖子當(dāng)著我的面吹牛廓潜,可吹牛的內(nèi)容都是我干的抵皱。 我是一名探鬼主播善榛,決...
    沈念sama閱讀 40,416評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼呻畸!你這毒婦竟也來(lái)了移盆?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,326評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤伤为,失蹤者是張志新(化名)和其女友劉穎咒循,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體绞愚,經(jīng)...
    沈念sama閱讀 45,782評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡叙甸,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,957評(píng)論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了位衩。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片裆蒸。...
    茶點(diǎn)故事閱讀 40,102評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖糖驴,靈堂內(nèi)的尸體忽然破棺而出僚祷,到底是詐尸還是另有隱情,我是刑警寧澤贮缕,帶...
    沈念sama閱讀 35,790評(píng)論 5 346
  • 正文 年R本政府宣布辙谜,位于F島的核電站,受9級(jí)特大地震影響感昼,放射性物質(zhì)發(fā)生泄漏装哆。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,442評(píng)論 3 331
  • 文/蒙蒙 一定嗓、第九天 我趴在偏房一處隱蔽的房頂上張望蜕琴。 院中可真熱鬧,春花似錦蜕乡、人聲如沸奸绷。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,996評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)号醉。三九已至,卻和暖如春辛块,著一層夾襖步出監(jiān)牢的瞬間畔派,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,113評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工润绵, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留线椰,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,332評(píng)論 3 373
  • 正文 我出身青樓尘盼,卻偏偏與公主長(zhǎng)得像憨愉,于是被迫代替她去往敵國(guó)和親烦绳。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,044評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容