1. 程式人生 > >spring cache ehcache2.x 基於spring boot 整合

spring cache ehcache2.x 基於spring boot 整合

引入快取
在pom.xml中引入依賴,新增如下內容:

    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
        <version>2.7.6</version>
    </dependency>

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

在Spring Boot主類中增加@EnableCaching註解開啟快取功能,如下:

@SpringBootApplication
@EnableCaching
public class Application {

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

}

在資料訪問介面中,增加快取配置註解,如:

@CacheConfig(cacheNames = "city")
public interface CityDao{

    @Cacheable
    User findByName(String name);
}

spring cache相關注解,此處就不必多說了,詳情
在Spring Boot中開啟EhCache非常簡單,只需要在工程中加入ehcache.xml配置檔案並在pom.xml中增加ehcache依賴,框架只要發現該檔案,就會建立EhCache的快取管理器

在src/main/resources目錄下建立:ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false"> 
    <diskStore path="java.io.tmpdir"/> 
    <defaultCache 
            maxElementsInMemory="10000" 
            eternal="false" 
            timeToIdleSeconds="3600" 
            timeToLiveSeconds="3600" 
            overflowToDisk="true" 
            maxElementsOnDisk="10000000" 
            diskPersistent="false" 
            diskExpiryThreadIntervalSeconds="120" 
            memoryStoreEvictionPolicy="LRU" 
            /> 
      <cache name="ehcache"
            maxElementsInMemory="10000" 
            eternal="false" 
            timeToIdleSeconds="3600" 
            timeToLiveSeconds="3600" 
            overflowToDisk="true" 
            maxElementsOnDisk="10000000" 
            diskPersistent="false" 
            diskExpiryThreadIntervalSeconds="120" 
            memoryStoreEvictionPolicy="LRU" 
        />      
</ehcache>

對於EhCache的配置檔案也可以通過application.properties檔案中使用spring.cache.ehcache.config屬性來指定,比如:

spring.cache.ehcache.config=classpath:ehcache.xml