天天看點

SpringBoot2 整合Ehcache元件,輕量級緩存管理一、Ehcache緩存簡介二、內建SpringBoot架構三、注解用法四、源代碼位址

本文源碼: GitHub·點這裡 || GitEE·點這裡

一、Ehcache緩存簡介

1、基礎簡介

EhCache是一個純Java的程序内緩存架構,具有快速、上手簡單等特點,是Hibernate中預設的緩存提供方。

2、Hibernate緩存

Hibernate三級緩存機制簡介:

一級緩存:基于Session級别配置設定一塊緩存空間,緩存通路的對象資訊。Session關閉後會自動清除緩存。

二級緩存:是SessionFactory對象緩存,可以被建立出的多個 Session 對象共享,二級緩存預設是關閉的,如果要使用需要手動開啟,并且依賴EhCache元件。

三級緩存:查詢緩存,配置開啟該緩存的情況下,重複使用一個sql查詢某個範圍内的資料,會進行緩存。

3、EhCache緩存特點

  • 快速,簡單,并且提供多種緩存政策;
  • 緩存資料有兩級:記憶體和磁盤,無需擔心容量問題;
  • 緩存資料會在虛拟機重新開機的過程中寫入磁盤;
  • 可以通過RMI、可插入API等方式進行分布式緩存;
  • 具有緩存和緩存管理器的偵聽接口;
  • 支援多緩存管理器執行個體,以及一個執行個體的多個緩存區域;
  • 提供Hibernate的緩存實作;

4、對比Redis緩存

Ehcache:直接在Jvm虛拟機中緩存,速度快,效率高,不适合處理大規模緩存資料,在分布式環境下,緩存資料共享操作複雜;

Redis:作為獨立的緩存中間件,在分布式緩存系統中非常好用,緩存資料共享,有效支撐大量資料緩存,支援哨兵模式,或者叢集模式的高可用成熟方案;

二、內建SpringBoot架構

1、核心依賴

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

2、加載配置

基礎配置

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

啟動類注解

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

3、配置詳解

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

    <!-- 作業系統緩存的臨時目錄,記憶體滿後寫入該目錄 -->
    <diskStore path="java.io.tmpdir"/>

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

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

配置參數說明

maxElementsOnDisk:磁盤緩存中最多可以存放的元素數量;

eternal:緩存中對象是否永久有效;

timeToIdleSeconds:當eternal=false時使用,緩存資料有效期(機關:秒),時間段内沒有通路該元素,将被清除;

timeToLiveSeconds:緩存資料的存活時間;

maxElementsInMemory:記憶體中最多可以存放的元素數量,overflowToDisk=true,則會将Cache中多出的元素放入磁盤檔案中,若overflowToDisk=false,則根據memoryStoreEvictionPolicy政策替換Cache中原有的元素;

diskExpiryThreadIntervalSeconds:磁盤緩存的清理線程運作間隔;

memoryStoreEvictionPolicy:緩存釋放政策,LRU會優先清理最少使用的緩存;

localTempSwap:持久化政策,當堆記憶體或者非堆記憶體裡面的元素已經滿了的時候,将其中的元素臨時的存放在磁盤上,重新開機後就會消失;

三、注解用法

@Service
public class CacheService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CacheService.class);

    @Resource
    private UserMapper userMapper ;

    @Cacheable(value="userEntity")  // 在緩存有效期内,首次查詢才通路資料庫
    public UserEntity getById (Integer id){
        // 通過日志,辨別方法是否執行
        LOGGER.info("getById..."+id);
        return userMapper.selectById(id) ;
    }

    @CacheEvict(value="userEntity",key = "#id") //該ID資料更新,清空該ID緩存
    public void updateUser(Integer id) {
        UserEntity user = new UserEntity() ;
        user.setId(id);
        user.setUserName("myCache");
        userMapper.updateById(user);
    }
}           

@Cacheable:注解标記在一個方法上,也可以标記在一個類上,标記在一個方法上表示該方法支援緩存,該方法被調用後将其傳回值緩存起來,下次同樣的請求參數執行該方法時可以直接從緩存中擷取結果,而不需要再次執行該方法。

@CacheEvict:注解标記在需要清除緩存元素的方法或類上的,當标記在一個類上時表示其中所有的方法的執行都會觸發緩存的清除操作,并且可以按照指定屬性清除。

四、源代碼位址

GitHub·位址
https://github.com/cicadasmile/middle-ware-parent
GitEE·位址
https://gitee.com/cicadasmile/middle-ware-parent