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>
<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")
<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) { ... }
@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) { ... }
引入 ehcache-spring-annotations 依賴,使用 @Cacheable、@TriggersRemove 註解,配置 ehcache:annotation-driven。
users、products、orders)<expiry> 配置 timeToLiveSeconds/timeToIdleSeconds@Cacheable(unless="#result==null") 反向)、佈隆過濾器