1. 程式人生 > >Spring Boot學習筆記(七)快取之ehche

Spring Boot學習筆記(七)快取之ehche

第一步 pom.xml新增依賴

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
            <version>2.1.1.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.10.6</version>
        </dependency>

第二步 新增ehche.xml

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

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

    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>

    <cache name="testCache"
                  maxElementsInMemory="10000"
                  eternal="false"
                  timeToIdleSeconds="120"
                  timeToLiveSeconds="120"
                  maxElementsOnDisk="10000000"
                  diskExpiryThreadIntervalSeconds="120"
                  memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

第三步 在application.yml中把ehche配上

cache:
    type: ehcache
    ehcache:
        config: ehcache.xml

第四步 在啟動類Application中新增@EnableCaching啟用快取

package org.test;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@ServletComponentScan //掃描servlet註解
@EnableCaching
public class Application {

    public static void main(String[] args) {
        org.springframework.boot.SpringApplication.run(Application.class, args);
    }

}

第五步 在DAO層新增快取註解,並設定要使用的快取配置名稱

package org.test.dao;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.cache.annotation.Cacheable;
import org.test.entity.TestTable;

import java.util.List;

@Mapper 
public interface TestTableDao {

      @Cacheable("testCache")
      List<TestTable> findAll();

      void insert (TestTable testTable);
}

第六步 測就完事了。

關於配置,網上搜了一個記錄一下: https://www.cnblogs.com/mymelody/p/5618198.html