1. 程式人生 > >springBoot簡單的ehCache快取實現

springBoot簡單的ehCache快取實現

本文簡單實現了一個springBoot的ehCache的實現

環境:windows+eclispe+springboot+maven+mybatis
本文是在一個已有的springboot+mybatis專案上實現的。資料庫可以自己隨便設計一個,使用什麼資料庫和讀取什麼資料和這裡的快取沒什麼關係,所以只記錄簡單的邏輯程式碼。

目錄:

一、匯入依賴包
二、建立實體entity和資料庫和mybatis配置
三、新增配置檔案
四、建立service類
五、編寫測試類

一、匯入依賴包

在pom.xml裡面新增兩個快取依賴包:

<dependency
>
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <dependency>

新增完依賴包後更新maven.

二、建立實體entity和資料庫和mybatis配置

這個就不做詳細說明了,可以自己定義一個entity,具體欄位自己定義,總之可以訪問到資料庫的資料就行,這一套流程自己寫一個。

三、新增配置檔案

在src/main/resources下建立一個配置檔案cache.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"
>
<diskStore path="java.io.tmpdir"/> <!-- 預設快取--> <defaultCache maxElementsInMemory="200" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" overflowToDisk="true" diskPersistent="false" memoryStoreEvictionPolicy="LRU" /> <!-- 自定義快取--> <cache name="myCacheName" maxElementsInMemory="200" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="3600" overflowToDisk="true" diskPersistent="false" memoryStoreEvictionPolicy="LRU"> </cache>

這個檔案會被自動掃描,注意不能修改cache.xml的名稱,這個名稱是預設的快取掃描配置檔名稱,因為springboot封裝了很多配置檔案,所有想要使用springBoot預設的掃描路徑就不要隨便修改配置檔名稱。(如果自定義配置檔案cache.xml的名稱,可以在application.properties裡面配置)

四、建立service類

在你的service類裡面建立一個方法,用於測試快取。如下:

@Service
public class PersonService{
    @Cacheable( value="myCacheName")  //這裡使用快取,名稱在配置檔案定義
    public List<Person> queryAll(){
        System.out.println(111);
        return PersonMapper.queryAll(); // 呼叫查詢資料庫的方法,查詢你的DB
    }

五、編寫測試類

程式碼如下:

/*下面兩個是springBoot單元測試的註解*/
@RunWith(SpringRunner.class)
@SpringBootTest
@EnableCaching  //在啟動類裡面啟用快取功能
public class Main{
    @Autowired 
    PersonService p;
    @Test
    public void aa(){
        p.queryAll();  //第一次呼叫,輸出111
        p.queryAll();  //第二次呼叫,使用cache,不輸出111
    }
}

注意:測試類裡面要直接呼叫service層使用快取註解的方法,如果測試類Main裡面先呼叫service層的a()方法,a()方法在呼叫使用了快取註解的b()方法,那麼這樣快取會失效。如:
在測試類Main裡面呼叫service裡面一個a()方法:

public class Main{
    @Autowired 
    PersonService p;
    @Test
    public void aa(){
        p.a();  //第一次呼叫,輸出111
        p.a();  //第二次呼叫,使用cache,不輸出111
    }
}

然後service的類這麼寫:

@Service
public class PersonService{
    public List<Person> a(){
        return b();
    }
    @Cacheable( value="myCacheName")  //這裡使用快取,名稱在配置檔案定義
    public List<Person> b(){
        System.out.println(111);
        return PersonMapper.queryAll(); // 呼叫查詢資料庫的方法,查詢你的DB
}

這樣呼叫最終輸出結果會輸出兩次111,也就是說快取失效。
上面只是簡單的實現了一個使用springBoot快取的過程,詳細的快取使用可以參考如下網址:springBoot快取詳解