Spring Cache 整合 Redis 實現(xiàn)高效緩存的方法
介紹
Spring Cache 是 Spring 框架提供的緩存抽象層,它簡化了在應用中添加緩存功能的過程,允許開發(fā)者通過注解方式輕松實現(xiàn)緩存邏輯,而無需關注具體的緩存實現(xiàn)細節(jié)。
- 緩存抽象:Spring Cache 不直接提供緩存實現(xiàn),而是定義了一套接口(如
Cache、CacheManager),支持多種緩存實現(xiàn)(如 Caffeine、EhCache、Redis 等)。 - 注解驅動:通過注解(如
@Cacheable、@CachePut、@CacheEvict)聲明緩存規(guī)則,無需手動編寫緩存邏輯。 - 透明集成:緩存操作與業(yè)務邏輯解耦,開發(fā)者只需關注業(yè)務代碼。
常用注解

@Cacheable
標記方法結果可被緩存。調(diào)用方法時,先檢查緩存:
@Cacheable(value = "users", key = "#id")
public User getUserById(Long id) {
// 從數(shù)據(jù)庫查詢用戶
return userRepository.findById(id);
}若緩存存在,直接返回緩存值,不執(zhí)行方法。
若緩存不存在,執(zhí)行方法并將結果存入緩存。
@CachePut
保證方法執(zhí)行,并將結果更新到緩存(常用于更新操作)。
@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
return userRepository.save(user);
}
@CacheEvict
移除緩存條目(常用于刪除操作)。
@CacheEvict(value = "users", key = "#id")
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
@Caching
組合多個緩存注解(如同時更新和刪除緩存)。
@Caching(
put = @CachePut(value = "users", key = "#user.id"),
evict = @CacheEvict(value = "userList", allEntries = true)
)
public User saveUser(User user) {
return userRepository.save(user);
}
@CacheConfig
在類級別統(tǒng)一配置緩存屬性(如 value、keyGenerator),簡化方法上的注解。
案例
- 添加依賴(Maven):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>- 啟用緩存:
在啟動類添加@EnableCaching注解。
@SpringBootApplication
@EnableTransactionManagement //開啟注解方式的事務管理
@Slf4j
@EnableCaching//開啟緩存功能
public class SkyApplication {
public static void main(String[] args) {
SpringApplication.run(SkyApplication.class, args);
log.info("server started");
}
}
- c端
/**
* 條件查詢
*
* @param categoryId
* @return
*/
@GetMapping("/list")
@ApiOperation("根據(jù)分類id查詢套餐")
@Cacheable(cacheNames = "setmealCache",key = "#categoryId")//key: setmealCache::categoryId
public Result<List<Setmeal>> list(Long categoryId) {
Setmeal setmeal = new Setmeal();
setmeal.setCategoryId(categoryId);
setmeal.setStatus(StatusConstant.ENABLE);
List<Setmeal> list = setmealService.list(setmeal);
return Result.success(list);
}
- 管理端
/**
* 新增套餐
* @param setmealDTO
* @return
*/
@PostMapping
@ApiOperation("新增套餐")
@CacheEvict(cacheNames = "setmealCache",key = "#setmealDTO.categoryId")
public Result save(@RequestBody SetmealDTO setmealDTO){
log.info("新增套餐:{}",setmealDTO);
setmealService.saveWithDish(setmealDTO);
return Result.success();
}
/**
* 刪除套餐
* @param ids
* @return
*/
@DeleteMapping
@ApiOperation("批量刪除套餐")
@CacheEvict(cacheNames = "setmealCache",allEntries = true)
public Result delete(@RequestParam List<Long> ids){
log.info("批量刪除套餐:{}",ids);
setmealService.deleteBatch(ids);
return Result.success();
}
/**
* 修改套餐起售停售狀態(tài)
* @param status
* @param id
* @return
*/
@PostMapping("/status/{status}")
@ApiOperation("修改套餐起售停售狀態(tài)")
@CacheEvict(cacheNames = "setmealCache",allEntries = true)
public Result startOrStop(@PathVariable("status") Integer status, Long id){
log.info("套餐起售或停售:{}",id);
setmealService.startOrStop(status,id);
return Result.success();
}注意事項
- 緩存鍵生成:默認使用方法參數(shù)生成鍵,可通過
key屬性自定義(SpEL 表達式),或配置KeyGenerator。 - 緩存穿透:可通過空值緩存(
@Cacheable(unless = "#result == null"))避免。 - 緩存更新:使用
@CachePut確保緩存與數(shù)據(jù)源一致性,避免直接修改緩存。 - 分布式緩存:在分布式系統(tǒng)中,推薦使用 Redis 等集中式緩存,避免本地緩存(如 Caffeine)的一致性問題。
通過 Spring Cache,開發(fā)者可以快速為應用添加緩存能力,提升系統(tǒng)性能,同時保持代碼簡潔易維護。
到此這篇關于Spring Cache 整合 Redis 實現(xiàn)高效緩存的文章就介紹到這了,更多相關Spring Cache Redis 高效緩存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- SpringBoot使用Cache集成Redis做緩存的保姆級教程
- SpringBoot集成Redis及SpringCache緩存管理示例詳解
- SpringBoot詳解整合Spring?Cache實現(xiàn)Redis緩存流程
- Spring項目中使用Cache?Redis實現(xiàn)數(shù)據(jù)緩存
- 分布式醫(yī)療掛號系統(tǒng)SpringCache與Redis為數(shù)據(jù)字典添加緩存
- 詳解SpringBoot2.0的@Cacheable(Redis)緩存失效時間解決方案
- SpringBoot+SpringCache實現(xiàn)兩級緩存(Redis+Caffeine)
- Spring中緩存注解@Cache的使用詳解
相關文章
JDK安裝與配置超級詳細教程(包含二個或多個JDK的同時安裝)
這篇文章主要給大家介紹了關于JDK安裝與配置(包含二個或多個JDK的同時安裝)的相關資料,對于Java學習者來說,一臺電腦拿到手肯定要配置JDK,但是對于新手來說還是容易出錯,需要的朋友可以參考下2023-10-10
java返回前端樹形結構數(shù)據(jù)的2種實現(xiàn)方式
近期項目有個需求,需要將組織機構數(shù)據(jù)拼成樹型結構返回至前端,下面這篇文章主要給大家介紹了關于java返回前端樹形結構數(shù)據(jù)的2種實現(xiàn)方式,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-05-05
Java使用WebFlux調(diào)用大模型實現(xiàn)智能對話
這篇文章主要為大家詳細介紹了Java如何使用WebFlux調(diào)用大模型實現(xiàn)智能對話效果,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2025-06-06
idea快捷鍵生成getter和setter,有構造參數(shù),無構造參數(shù),重寫toString方式
這篇文章主要介紹了java之idea快捷鍵生成getter和setter,有構造參數(shù),無構造參數(shù),重寫toString方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11

