欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring Cache 整合 Redis 實現(xiàn)高效緩存的方法

 更新時間:2025年08月21日 10:00:14   作者:跟著豪哥學Java  
SpringCache是Spring框架的緩存抽象層,通過注解簡化緩存邏輯,支持Caffeine、EhCache、Redis等實現(xiàn),接下來通過本文給大家介紹Spring Cache整合Redis實現(xiàn)高效緩存的方法,感興趣的朋友跟隨小編一起看看吧

介紹

Spring Cache 是 Spring 框架提供的緩存抽象層,它簡化了在應用中添加緩存功能的過程,允許開發(fā)者通過注解方式輕松實現(xiàn)緩存邏輯,而無需關注具體的緩存實現(xiàn)細節(jié)。

  1. 緩存抽象:Spring Cache 不直接提供緩存實現(xiàn),而是定義了一套接口(如 CacheCacheManager),支持多種緩存實現(xiàn)(如 Caffeine、EhCache、Redis 等)。
  2. 注解驅動:通過注解(如 @Cacheable、@CachePut、@CacheEvict)聲明緩存規(guī)則,無需手動編寫緩存邏輯。
  3. 透明集成:緩存操作與業(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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論