首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring Cache 抽象與實戰:@Cacheable、@CacheEvict、@CachePut 完整指南

     編輯:Java 相關知識

Spring Cache 提供宣告式快取抽象,支援 JDK ConcurrentMap、Ehcache、Caffeine、Redis 等多種後端。核心三大註解:@Cacheable(讀+寫)、@CacheEvict(刪除)、@CachePut(僅寫)。

核心註解對照

註解行為典型場景
@Cacheable先查快取,命中回傳;未命中執行方法並存入查詢方法、昂貴運算
@CachePut總是執行方法,結果存入快取新增/更新方法
@CacheEvict執行方法前/後移除快取條目刪除/批量更新方法

基本配置


<beans xmlns:cache="https://www.springframework.org/schema/cache">
    <cache:annotation-driven />
</beans>

儲存策略一:ConcurrentMap(簡單/開發環境)


<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
    <property name="caches">
        <set>
            <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="default"/>
            <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="books"/>
        </set>
    </property>
</bean>

對應註解:@Cacheable(value="books")

儲存策略二:Ehcache(生產環境常用)


<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" 
      p:cache-manager-ref="ehcache"/>
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" 
      p:config-location="ehcache.xml"/>

ehcache.xml 定義快取區域、過期策略、持久化等。

進階用法

條件式快取


@Cacheable(value="books", condition="#isbn.length() > 10")
public Book findBook(String isbn) { ... }

@Cacheable(value="books", unless="#result == null")
public Book findBook(String isbn) { ... }

自定義 Key 生成


@Cacheable(value="books", key="#isbn")
@Cacheable(value="books", key="T(com.example.util.KeyGenerator).generate(#root.args)")

多快取操作組合


@Caching(evict = {
    @CacheEvict(value="books", key="#isbn"),
    @CacheEvict(value="bookStats", allEntries=true)
})
public void updateBook(String isbn, Book book) { ... }

Spring 3.1 之前版本相容

引入 ehcache-spring-annotations 依賴,使用 @Cacheable、@TriggersRemove 註解,配置 ehcache:annotation-driven。

最佳實踐建議

  1. 快取名稱語義化:按業務域劃分(users、products、orders)
  2. TTL 策略:Ehcache <expiry> 配置 timeToLiveSeconds/timeToIdleSeconds
  3. 快取穿透防護:空值快取(@Cacheable(unless="#result==null") 反向)、佈隆過濾器
  4. 快取雪崩防護:過期時間加隨機抖動、多級快取
  5. 監控指標:命中率、驅逐數、平均獲取延遲
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved