在集群環境下,Ehcache 通過 RMI 實現多節點緩存同步。本文提供一份生產級 ehcache.xml 配置範本,詳細解析 手動發現與組播自動發現兩種對等節點發現策略,並深入講解緩存複製參數調優,助你構建高可用分布式緩存體系。
<ehcache xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd">
<!-- 磁盤存儲路徑,防重啟數據丟失 -->
<diskStore path="java.io.tmpdir"/>
<!-- 節點監聽工廠 (接收端) -->
<cacheManagerPeerListenerFactory
class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
properties="hostName=10.1.35.111, port=40001, socketTimeoutMillis=2000"/>
<!-- 節點發現工廠 (發送端) -->
<cacheManagerPeerProviderFactory
class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
properties="peerDiscovery=manual,
hostName=10.1.35.111,
port=40002,
rmiUrls=//10.1.35.111:40001/BaseDataCache|//10.1.35.112:40001/BaseDataCache,
timeToLive=0"/>
<!-- 預設緩存策略 -->
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="600" timeToLiveSeconds="86400"
overflowToDisk="false"/>
<!-- 業務緩存:基礎數據緩存 -->
<cache name="BaseDataCache"
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="60000"
timeToLiveSeconds="600000"
memoryStoreEvictionPolicy="LFU">
<!-- RMI 緩存複製監聽器 -->
<cacheEventListenerFactory
class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
properties="replicateAsynchronously=true,
replicatePuts=true,
replicatePutsViaCopy=true,
replicateUpdates=true,
replicateUpdatesViaCopy=true,
replicateRemovals=true"/>
</cache>
</ehcache>
| 策略 | 配置關鍵字 | 適用場景 | 優缺點 |
|---|---|---|---|
| 手動發現 | peerDiscovery=manualrmiUrls=//host:port/cacheName |
節點固定、數量少、生產環境推薦 | 配置明確、穩定可控;擴容需修改配置 |
| 組播自動發現 | peerDiscovery=automaticmulticastGroupAddress=230.0.0.1 |
節點動態增減、開發測試環境 | 零配置擴容;網絡不通時易失效、組播風暴風險 |
timeToLive (TTL) 含義:控制組播包傳播範圍,0=本機,1=子網,32=站點,255=無限制。手動模式下設為 0 即可。
RMICacheReplicatorFactory 核心屬性:
replicateAsynchronously=true:強烈建議開啟異步複製,避免同步阻塞業務線程。replicatePuts/Updates/Removals=true:全開啟保證數據最終一致性。replicatePutsViaCopy/UpdatesViaCopy=true:傳遞對象副本而非引用,防止遠程節點修改本地對象。asynchronousReplicationIntervalMillis=1000:異步批次間隔,平衡一致性與性能。maxElementsInMemory:內存最大對象數,超出則依策略淘汰或溢寫磁盤。eternal="false":非永久,需配合 TTL/TTI 過期。timeToIdleSeconds (TTI):閒置超時,兩次訪問間隔超過即過期。timeToLiveSeconds (TTL):生存超時,從創建起計算最大存活時間。overflowToDisk="true":內存不足時溢寫磁盤,配合 diskStore 實現持久化。memoryStoreEvictionPolicy="LFU":最少使用淘汰,適合熱點數據場景;可選 LRU、FIFO。PeerListener 與 PeerProvider 端口不同,避免衝突(示例 40001/40002)。Serializable,注意 serialVersionUID 管理。cache hits/misses、replication queue size、RMI latency。hostName 是否為可訪問 IP(非 127.0.0.1),組播模式驗證網絡組播支持。cacheEventListenerFactory 配置在具體 <cache> 內,而非 defaultCache。ClassNotFoundException:集群節點部署一致,緩存對象類路徑完全一致。合理配置 Ehcache 分布式緩存,能顯著降低數據庫壓力,提升系統響應速度。根據業務規模選擇發現策略,調優複製參數,是構建高性能 Java 集群應用的關鍵一環。