SpringBoot系統搭建集成-014-如何使用ehcache緩存

Lison <[email protected]>, v1.0.0, 2019.10.05

SpringBoot系統搭建集成-014-如何使用ehcache緩存

Spring Boot的cache支持多種緩存,參考緩存支持,其中常用的有EhCache和Redis,Redis需要安裝redis服務器,而EhCache不依賴任何第三方軟件,只需引入jar即可。下面主要介紹ehcache的集成方法。

添加依賴

在pom.xml裏添加ehcache相關的依賴

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

創建ehcache.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
 <defaultCache
            maxElementsInMemory="20000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"/>

    <!--
    緩存文件名:user,同樣的可以配置多個緩存
    maxElementsInMemory:內存中最多存儲
    eternal:外部存儲
    overflowToDisk:超出緩存到磁盤
    diskPersistent:磁盤持久化
    timeToLiveSeconds:緩存時間
    diskExpiryThreadIntervalSeconds:磁盤過期時間
    -->
    <cache name="user"
           maxElementsInMemory="20000"
           eternal="true"
           overflowToDisk="true"
           diskPersistent="false"
           timeToLiveSeconds="0"
           diskExpiryThreadIntervalSeconds="120"/>

</ehcache>

cache的屬性說明:

  • name:緩存的名稱。
  • maxElementsInMemory:緩存中最大元素個數。0表示不限制
  • eternal:對象是否永久有效,一但設置了,timeout將不起作用,元素永久存在。
  • clearOnFlush:內存數量最大時是否清除。
  • timeToIdleSeconds : 設置對象在失效前的允許閒置時間(單位:秒)。僅當eternal=false對象不是永久有效時使用,可選屬性,默認值是0,也就是可閒置時間無窮大。
  • timeToLiveSeconds:設置對象在失效前允許存活時間(單位:秒)。最大時間介於創建時間和失效時間之間。僅當eternal=false對象不是永久有效時使用,默認是0.,也就是對象存活時間無窮大。
  • diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒。
  • diskPersistent:是否在VM重啓時存儲硬盤的緩存數據。默認值是false。
  • maxElementsOnDisk:硬盤最大緩存個數。
  • overflowToDisk:當內存中對象數量達到maxElementsInMemory時,Ehcache將會對象寫到磁盤中。
  • diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每個Cache
  • 都應該有自己的一個緩衝區。
  • maxEntriesLocalDisk:當內存中對象數量達到maxElementsInMemory時,Ehcache將會對象寫到磁盤中。
  • memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你可以設置爲FIFO(先進先出)或是LFU(較少使用)。

配置ehcache配置

spring:
  cache:
    ehcache:
      config: ehcache.xml

開啓緩存支持

在啓動類上添加註解**@EnableCaching**以開啓緩存支持。

@EnableCaching
@MapperScan("com.github.cundream.springbootbuilding.mapper")
@SpringBootApplication
public class SpringbootbuildingApplication  extends SpringBootServletInitializer {


    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SpringbootbuildingApplication.class);
    }
    public static void main(String[] args) {
        SpringApplication.run(SpringbootbuildingApplication.class, args);
    }

}

代碼中使用緩存

Spring提供了4個聲明式緩存註解:

註解 解釋
@Cacheable 在方法執行前Spring先查看緩存中是否存在,如果存在,則直接返回緩存數據,若不存在則調用方法並將方法返回值放進緩存
@CachePut 無論怎樣,都會將方法的返回值放到緩存中。@CachePut的屬性與@Cacheable保持一致
@CacheEvict 將一條或多條數據從緩存中刪除。
@Caching 可以通過@Caching註解組合多個註解策略在一個方法上


​ 1、添加緩存

添加緩存只需要在方法上面添加緩存註解即可,我們對com.github.cundream.springbootbuilding.service.impl.UserServiceImpl#getUserList`方法做如下修改:

 /**
     *
     * @param userId
     * @return
     */
    @Cacheable(cacheNames = "users", key = "#userId")
    @Override
    public User getUserListInfo(Long userId) {
        return  userMapper.getUserInfoById(userId);

    }

2、刪除緩存
當我們刪除用戶、修改用戶等操作時,需要把緩存也更新。下面例子使用@CacheEvict註解來刪除緩存

@CacheEvict(value = "users",key = "#id")
public void evictUser(Long id) {
    System.out.println("evict user:" + id);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章