SpringCache缓存快速实现注解

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() {~~~~}

猜你喜欢

转载自blog.csdn.net/sunyunfei1994/article/details/136072536