Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Spring 整合 ehcache:用註解完成查詢快取與即時失效(上篇)

上一篇談完了 Spring Cache 與 ehcache 的基礎觀念,本篇就正式動手:把 ehcache 接進 Spring,用註解讓查詢方法自動走快取,並在資料變動時即時更新或清除。先從引入相依套件開始。

零、引入 jar

<!-- 引入 ehcache 快取 -->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.8.3</version>
</dependency>

一、設定 ehcache.xml

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="ehcache.xsd"
        updateCheck="true" monitoring="autodetect"
        dynamicConfig="true">

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

    <defaultCache
        maxEntriesLocalHeap="10000"
        eternal="false"
        overflowToDisk="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        diskSpoolBufferSizeMB="30"
        maxEntriesLocalDisk="10000000"
        diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>

    <cache name="myCache"
        maxEntriesLocalHeap="10000"
        maxEntriesLocalDisk="1000"
        eternal="false"
        diskSpoolBufferSizeMB="30"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        memoryStoreEvictionPolicy="LFU"
        transactionalMode="off">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

二、在 Spring 主設定檔中啟用註解快取

先在 spring.xml 的 beans 節點補上 aop 與 cache 兩個命名空間(https://www.springframework.org/schema/cache,對應的 xsd 為 spring-cache-3.2.xsd),接著加入:

<!-- 啟用快取註解;必須宣告在主設定檔才會生效 -->
<cache:annotation-driven cache-manager="ehcacheManager"/>

<!-- cacheManager 工廠類,指定 ehcache.xml 的位置 -->
<bean id="ehcacheManagerFactory"
        class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="configLocation" value="classpath:ehcache.xml" />
</bean>

<!-- 宣告 cacheManager -->
<bean id="ehcacheManager"
        class="org.springframework.cache.ehcache.EhCacheCacheManager">
    <property name="cacheManager" ref="ehcacheManagerFactory" />
</bean>

到這裡,快取相關的基礎設定就完成了。

三、實體類必須可序列化

這是最容易被忽略的一步:要進入 ehcache(尤其是溢出到磁碟時)的物件,一定要實作 Serializable 並宣告 serialVersionUID。以下沿用先前 AOP 日誌用的 SystemLog 當示範:

package org.shop.entity;

import java.io.Serializable;
import java.util.Date;

public class SystemLog implements Serializable {

    private static final long serialVersionUID = -6579533328390250520L;

    private String id;
    private String description;
    private String method;
    private Long logType;
    private String requestIp;
    private String exceptioncode;
    private String exceptionDetail;
    private String params;
    private String createBy;
    private Date createDate;

    // getter / setter 略
}

四、DAO 與 Service 介面

package org.shop.dao;

import org.shop.entity.SystemLog;

public interface SystemLogMapper {
    int deleteByPrimaryKey(String id);
    int insert(SystemLog record);
    int insertSelective(SystemLog record);
    SystemLog selectByPrimaryKey(String id);
    int updateByPrimaryKeySelective(SystemLog record);
    int updateByPrimaryKey(SystemLog record);
    int count();
}
public interface SystemLogService {
    int deleteSystemLog(String id);
    int insert(SystemLog record);
    int insertTest(SystemLog record);
    SystemLog findSystemLog(String id);
    int updateSystemLog(SystemLog record);
    int count();
}

接著在 Service 實作類的查詢方法上標 @Cacheable(value = "myCache"),並在新增/修改/刪除方法上標 @CacheEvict correspondingly 清除舊資料,就能達到「查詢走快取、寫入即失效」的效果。實作細節與測試程式請見下篇。

延伸閱讀:Spring 中如何配置 Hibernate 事務、Struts2 整合 Spring 方法及原理、以 Spring 設計 RESTful Web Services、Spring 3.2.4 + Quartz 2.2.0 整合實例。

Copyright © Linux教程網 All Rights Reserved