Spring Cache
Spring Cache是Spring框架提供的緩存抽象層,通過注解和自動化配置,簡化應用中對緩存的操作,支持多種緩存實現(如Redis、Ehcache、Caffeine)。
1. 核心特性
- 聲明式緩存:通過注解(如@Cacheable、@CacheEvict)聲明緩存行為,無需手動編寫緩存邏輯。
- 多緩存實現支持:兼容Redis、Ehcache、Caffeine等緩存工具,通過統一接口切換實現。
- 與Spring無縫集成:基于AOP動態代理,攔截方法調用自動處理緩存。
- 靈活的緩存策略:支持條件緩存(condition)、緩存鍵生成(key)、緩存過期等配置。
2. 核心注解
注解 | 作用 | 常用參數 | 示例 |
---|---|---|---|
@EnableCaching | 開啟緩存注解功能,通常加在啟動類上 | ||
@Cacheable | 方法結果緩存。在方法執行前先查詢緩存中是否有數據,如果有數據則直接返回緩存數據;如果沒有緩存數據,調用方法并將方法返回值放到緩存中 | value(緩存名)、key(鍵)、condition(條件) | 緩存數據庫查詢結果 |
@CachePut | 更新緩存,將方法的返回值放到緩存中 | value(緩存名)、key(鍵)、condition(條件) | 數據更新后刷新緩存 |
@CacheEvict | 刪除緩存,將一條或多條數據從緩存中刪除 | allEntries(清空所有鍵)、beforeInvocation(執行前刪除) | 數據清除時刪除緩存 |
1. @Cacheable:
? ? ? ?作用:標記方法的結果需要被緩存。當方法被調用時,先檢查緩存是否存在對應鍵值,若存在則直接返回緩存值,否則執行方法并將結果存入緩存。
? ? ? ? 使用場景:查詢操作(如數據庫查詢、復雜計算等)。
? ? ? ? 示例:
@Cacheable(value = "userCache", key = "#userId", condition = "#userId != null")
public User getUserById(Long userId) {return userRepository.findById(userId).orElse(null);
}
2. @CachePut:
? ? ? ? 作用:更新緩存。無論緩存是否存在,都會執行方法,并將結果更新到緩存中。
? ? ? ? 適用場景:新增或更新操作(如更新用戶信息后同步緩存)。
? ? ? ? 示例:
@CachePut(value = "userCache", key = "#user.id")
public User updateUser(User user) {return userRepository.save(user);
}
3. @CacheEvict
? ? ? ? 作用:刪除緩存。根據條件清除指定鍵或整個緩存區的數據。
? ? ? ? 適用場景:刪除操作(如用戶刪除后清理緩存)。
? ? ? ??示例:
@CacheEvict(value = "userCache", key = "#userId")
public void deleteUser(Long userId) {userRepository.deleteById(userId);
}// 清空整個緩存區
@CacheEvict(value = "userCache", allEntries = true)
public void clearAllUserCache() {}
3.使用步驟(以Redis為例)
添加依賴:
<!-- Spring Boot Starter Cache -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Redis 集成 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置緩存類型與Redis:
# application.properties
spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=6379
# 可選:設置緩存過期時間(單位:毫秒)
spring.cache.redis.time-to-live=60000
啟用緩存:在啟動類添加@EnableCaching
@SpringBootApplication
@EnableCaching
public class MyApp { ... }
在Service層使用注解:
// 僅當參數id>10時緩存
@Cacheable(value = "users", condition = "#id > 10")// 結果不為null時緩存
@Cacheable(value = "users", unless = "#result == null")
4. 緩存鍵與條件控制
自定義緩存鍵(SpEL表達式)
@Cacheable(value = "orders", key = "#userId + ':' + #status")
public List<Order> getOrdersByUserAndStatus(Long userId, String status) { ... }
條件緩存(condition和unless)
// 僅當參數id>10時緩存
@Cacheable(value = "users", condition = "#id > 10")// 結果不為null時緩存
@Cacheable(value = "users", unless = "#result == null")
5. 適用場景
- 高頻讀低頻寫:如商品詳情頁、用戶信息查詢。
- 耗時計算:緩存復雜計算結果(如報表生成)。
- API限流:緩存接口調用次數。
- 會話管理:分布式環境下用戶狀態緩存。
Spring Cache通過簡化緩存邏輯與代碼解耦,顯著提升了開發效率。結合Redis等高性能緩存工具,能夠輕松應對高并發場景。