作者:ramostear
https://www.jianshu.com/p/f4126ee58df1
本次內容主要介紹基于Ehcache 3.0來快速實作Spring Boot應用程式的資料快取功能,在Spring Boot應用程式中,我們可以通過Spring Caching來快速搞定資料快取,
接下來我們將介紹如何在三步之內搞定 Spring Boot 快取,
1. 創建一個Spring Boot工程
你所創建的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 = "https://www.cnblogs.com/javastack/p/personService")
public class PersonService {
@Cacheable(cacheNames = "person",key = "#id")
public Person getPerson(Long id){
Person person = new Person(id,"ramostear","[email protected]");
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 = "https://www.cnblogs.com/javastack/p/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":"[email protected]"}
此時在觀察控制臺輸出的日志資訊:
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
由于我們是第一次請求API,沒有任何快取資料,因此,Ehcache創建了一條快取資料,可以通過CREATED看一了解到,
我們在ehcache.xml檔案中將快取過期時間設定成了1分鐘(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
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
第一條日志提示快取已經過期,第二條日志提示Ehcache重新創建了一條快取資料,
結束語
在本次案例中,通過簡單的三個步驟,講解了基于 Ehcache 的 Spring Boot 應用程式快取實作,
文章內容重在快取實作的基本步驟與方法,簡化了具體的業務代碼,有興趣的朋友可以自行擴展,期間遇到問題也可以隨時與我聯系,
推薦去我的博客閱讀更多:
1.Java JVM、集合、多執行緒、新特性系列教程
2.Spring MVC、Spring Boot、Spring Cloud 系列教程
3.Maven、Git、Eclipse、Intellij IDEA 系列工具教程
4.Java、后端、架構、阿里巴巴等大廠最新面試題
覺得不錯,別忘了點贊+轉發哦!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/189831.html
標籤:Java
