Spring Boot 集成 Ehcache 緩存


做者:譚朝紅html

www.ramostear.com/articles/spring_boot_ehcache.htmljava


本次內容主要介紹基於Ehcache 3.0來快速實現Spring Boot應用程序的數據緩存功能。 在Spring Boot應用程序中,咱們能夠經過Spring Caching來快速搞定數據緩存。

接下來咱們將介紹如何在三步以內搞定 Spring Boot 緩存。

1. 建立一個Spring Boot工程

你所建立的Spring Boot應用程序的maven依賴文件至少應該是下面的樣子:web

  
  
   
   
            
   
   
  1. 面試

  2. spring

  3. apache

  4. 編程

  5. json

  6. 後端

  7. api





<?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@EnableCachingpublic 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 = "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的緩存功能。接下來,咱們將測試一下緩存的實際狀況。

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 = "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@NoArgsConstructorpublic 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 ms2019-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 null2019-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 應用程序緩存實現。

文章內容重在緩存實現的基本步驟與方法,簡化了具體的業務代碼,有興趣的朋友能夠自行擴展,期間遇到問題也能夠隨時與我聯繫。


- END -


關注微信公衆號,在後臺回覆關鍵字:Java,能夠獲取一份整理的 Java 最新技術乾貨。

最近乾貨分享

Mybatis多數據源動態切換,原來這麼簡單!

21道 Redis 常見面試題,必須掌握!

一塊兒來了解下 Spring Data JPA

推薦 SpringBoot 微信點餐開源系統


看完本文有收穫?請轉發分享給更多人

本文分享自微信公衆號 - Java後端編程(java_hdbc)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索