【Springboot】Springboot整合Ehcache

剛剛項目上線了,記錄下使用的技術......java

EhCache 是一個純Java的進程內緩存框架,具備快速、精幹等特色,是Hibernate中默認的CacheProvider。api

Ehcache的特色緩存

(1)快速簡單,具備多種緩存策略框架

(2)緩存數據有兩級爲內存和磁盤,緩存數據會在虛擬機重啓的過程當中寫入磁盤分佈式

(3)能夠經過RMI、可插入API等方式進行分佈式緩存ide

(4)具備緩存和緩存管理器的偵聽接口spa

(5)支持多緩存管理器實例,以及一個實例的多個緩存區域。並提供Hibernate的緩存實現code

項目涉及到的是報文協議轉換,使用到各種api或報文格式模版須要緩存至內存中以減小報文轉換耗時,選擇Ehcache也是比較適合的,快速、簡單xml

話很少說,搭個小demo對象

1、Springboot整合Ehcache

  1. 配置依賴

    pom.xml中添加ehcache依賴   

  <dependency>

        <groupId>net.sf.ehcache</groupId>

        <artifactId>ehcache</artifactId>

  </dependency>

 

  2.配置ehcache.xml

 

<?xml version="1.0" encoding="UTF-8"?>

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"

updateCheck="false">

 

<!--

        磁盤存儲:將緩存中暫時不使用的對象,轉移到硬盤,相似於Windows系統的虛擬內存

        path:指定在硬盤上存儲對象的路徑

        path能夠配置的目錄有:

            user.home(用戶的家目錄)

            user.dir(用戶當前的工做目錄)

            java.io.tmpdir(默認的臨時目錄)

            ehcache.disk.store.dir(ehcache的配置目錄)

            絕對路徑(如:d:\\ehcache)

        查看路徑方法:String tmpDir = System.getProperty("java.io.tmpdir");

     -->

<diskStore path="java.io.tmpdir" />

<!--

        eternal:緩存內容是否永久存儲在內存;該值設置爲true時,timeToIdleSeconds和timeToLiveSeconds兩個屬性的值就不起做用了

        maxElementsInMemory:設置了緩存的上限,最多存儲多少個記錄對象

        timeToIdleSeconds:緩存建立之後,最後一次訪問緩存的日期至失效之時的時間間隔;默認值是0,也就是可閒置時間無窮大

        timeToLiveSeconds:緩存自建立日期起至失效時的間隔時間;默認是0.也就是對象存活時間無窮大

        overflowToDisk:若是內存中的數據超過maxElementsInMemory,是否使用磁盤存儲

        diskPersistent:磁盤存儲的條目是否永久保存

        maxElementsOnDisk:硬盤最大緩存個數

        memoryStoreEvictionPolicy:默認策略是 LRU(最近最少使用)。你能夠設置爲FIFO(先進先出)或是LFU(較少使用)

     

     -->

 

<cache name="usercache" eternal="false" maxElementsInMemory="10000"

overflowToDisk="true" diskPersistent="false" maxElementsOnDisk="0" timeToIdleSeconds="0" timeToLiveSeconds="0"

memoryStoreEvictionPolicy="LRU" />

</ehcache>

3.配置啓用ehcache註解

1 @SpringBootApplication
2 @EnableCaching 3 public class App {
4     public static void main(String[] args) {
5         SpringApplication.run(App.class, args);
6     }
7 }

4.

相關文章
相關標籤/搜索