Spring Boot 揭祕與實戰(二) 資料快取篇 - EhCache

樑桂釗發表於2017-01-05

本文,講解 Spring Boot 如何整合 EhCache,實現快取。

部落格地址:blog.720ui.com/

在閱讀「Spring Boot 揭祕與實戰(二) 資料快取篇 - 快速入門」後,對 Spring Boot 整合快取機制有一定了解後,我們來了解下 EhCache 的使用。

EhCache 整合

EhCache 是一個純 Java 的程式內快取框架,具有快速、精幹等特點,是 Hibernate 中預設的 CacheProvider。

在 Spring Boot 中整合 EhCache 非常容易,只需要兩個步驟。

首先,在 pom.xml 中增加EhCache 依賴。

<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>複製程式碼

第二步,在 src/main/resources 目錄下建立 ehcache.xml。

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd">
    <cache name="ehcache"
           maxElementsInMemory="1000"
           timeToLiveSeconds="300">
    </cache>
</ehcache>複製程式碼

其中,maxElementsInMemory,表示快取最大數目。 timeToLiveSeconds: ,表示設定物件在失效前允許存活時間(單位:秒)。

如果想對 ehcache.xml 更深入的瞭解,可以參考 www.ehcache.org/ehcache.xml…

執行起來,控制檯列印的日誌資訊,說明已經是EhCacheManager例項,說明 EhCache 開啟成功了。

Bean 'cacheManager' of type [class org.springframework.cache.ehcache.EhCacheCacheManager]複製程式碼

原始碼

相關示例完整程式碼: springboot-action

(完)

更多精彩文章,盡在「服務端思維」微信公眾號!

Spring Boot 揭祕與實戰(二) 資料快取篇 - EhCache

相關文章