SpringCache缓存快速实现注解

本文介绍了如何在SpringBoot应用中使用SpringCache框架集成Redis,通过注解如@EnableCaching开启缓存功能,以及@CachePut存入缓存、@Cacheable查询缓存、@CacheEvict清理缓存的方法和示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringCache是一个框架,只需要添加一个注解,就能实现缓存功能的实现,常用的就是Redis的缓存实现

依赖

spring-boot-starter-data-redis  与   spring-boot-starter-cache

@EnableCatching标注在启动类上,开启基于注解的缓存功能

@CachePut 将方法的缓存值放入到缓存中

@CachePut(value=“userCache”,key=“result.id”)

@PostMapping(“/user”)

public User save (@RequestBody User user){

userMapper.insert(user);       

return user;

}其中value用于指定缓存内存区域的名称,key缓存数据的key支持SPEL表达式如#user.id  #result.id

@Cacheable在方法执行前查看缓存中是否有数据,如果有直接返回,如果没有,将调查方法查询数据库结果返回值放入到缓存中

@Cacheable(value="userCache",key="#id")

@GetMapping("/user/{id}")

public User findById(@PathVariable Long id ){~~~~}

@CacheEvict清理指定缓存

@CacheEvict(value = "userCache", key = "#id")   清理指定key的缓存@DeleteMapping("/user/{id}") 
public void deleteById(@PathVariable Long id) {~~~}

@CacheEvict(value = "userCache", allEntries = true)  清理整个value区域所有缓存
@DeleteMapping("/user")
public void deleteAll() {~~~~}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值