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依賴文件至少應(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>
依賴說(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)行注釋,告訴Spring 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)。
以上就是本次介紹的全部知識(shí)點(diǎn)內(nèi)容,感謝大家的學(xué)習(xí)和對(duì)腳本之家的支持。
- 在Mybatis中使用自定義緩存ehcache的方法
- SpringBoot2 整合Ehcache組件,輕量級(jí)緩存管理的原理解析
- SpringBoot中Shiro緩存使用Redis、Ehcache的方法
- 使用ehcache三步搞定springboot緩存的方法示例
- 詳解Spring Boot Oauth2緩存UserDetails到Ehcache
- spring-boot整合ehcache實(shí)現(xiàn)緩存機(jī)制的方法
- Spring Boot緩存實(shí)戰(zhàn) EhCache示例
- Java Ehcache緩存框架入門(mén)級(jí)使用實(shí)例
- 詳解SpringBoot緩存的實(shí)例代碼(EhCache 2.x 篇)
- Spring+EHcache緩存實(shí)例詳解
- 詳解Spring MVC 集成EHCache緩存
- Java緩存ehcache的使用步驟
相關(guān)文章
Java虛擬機(jī)執(zhí)行引擎知識(shí)總結(jié)
這篇文章主要介紹了有關(guān)Java虛擬機(jī)執(zhí)行引擎的知識(shí),文中實(shí)例簡(jiǎn)單易懂,方便大家更好的學(xué)習(xí),有興趣的朋友可以了解下2020-06-06
IDEA導(dǎo)入geoserver項(xiàng)目的詳細(xì)步驟及注意事項(xiàng)
由于GeoServer是基于Java開(kāi)發(fā)的。因此在安裝之前,必須確保安裝了Java。本文給大家分享IDEA導(dǎo)入geoserver項(xiàng)目的詳細(xì)步驟及注意事項(xiàng),感興趣的朋友一起看看吧2021-06-06
Java類(lèi)的序列化版本唯一標(biāo)識(shí)符serialVersionUID使用
serialVersionUID是一個(gè)類(lèi)的序列化版本唯一標(biāo)識(shí)符,用于確保在反序列化過(guò)程中類(lèi)的實(shí)例與序列化文件中的類(lèi)版本相匹配,它在版本兼容性和安全性方面起著關(guān)鍵作用2025-01-01
Spring Boot使用Value注解給靜態(tài)變量賦值的方法
這篇文章主要介紹了Spring Boot使用Value注解給靜態(tài)變量賦值的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-07-07
elasticsearch構(gòu)造Client實(shí)現(xiàn)java客戶端調(diào)用接口示例分析
這篇文章主要為大家介紹了elasticsearch構(gòu)造Client實(shí)現(xiàn)java客戶端調(diào)用接口示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-04-04
rabbitmq五種模式詳解(含實(shí)現(xiàn)代碼)
這篇文章主要介紹了rabbitmq五種模式詳解(含實(shí)現(xiàn)代碼),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04
java基于jdbc實(shí)現(xiàn)簡(jiǎn)單學(xué)生管理系統(tǒng)
本文主要主要介紹了java連接mysql數(shù)據(jù)庫(kù)的一個(gè)簡(jiǎn)單學(xué)生系統(tǒng),通過(guò)jdbc連接數(shù)據(jù)庫(kù)。文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-10-10
導(dǎo)入maven項(xiàng)目各個(gè)注解均報(bào)錯(cuò)的解決方案
這篇文章主要介紹了導(dǎo)入maven項(xiàng)目各個(gè)注解均報(bào)錯(cuò)的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12
詳解Spring依賴注入的三種方式使用及優(yōu)缺點(diǎn)
這篇文章主要介紹了spring依賴注入的三種方式的使用方法,以及優(yōu)缺點(diǎn)的介紹,通過(guò)代碼示例介紹的非常詳細(xì),感興趣的小伙伴可以參考一下2023-04-04
java數(shù)組及arrays類(lèi)對(duì)數(shù)組的操作實(shí)例
下面小編就為大家?guī)?lái)一篇java數(shù)組及arrays類(lèi)對(duì)數(shù)組的操作實(shí)例。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-10-10

