一、介绍
springCache是一个框架,实现了基于注解的缓存功能,只需要简单的加一个注解,就可以实现缓存
springCache提供了一层抽象,底层可以切换不同的缓存实现,如:
EHCache
Caffeine
Redis
springCache常用注解:
@EnableCaching :开启缓存注解功能,通常加在实现类上
@Cacheable : 在方法执行前,先判断缓存中是否有数据,如果有,则返回缓存数据,如果没有数据,调用方法将返回值放到缓存中
@CachePut :将方法的返回值放到缓存中
@CacheEvict :将一条或多条数据从缓存中删除
二、项目中应用
1、引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
2、在启动类加入开启缓存的注解 @EnableCaching
package com.sky;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@EnableTransactionManagement //开启注解方式的事务管理
@EnableCaching //开启缓存的注解
@Slf4j
public class SkyApplication {
public static void main(String[] args) {
SpringApplication.run(SkyApplication.class, args);
}
}
3、 @Cacheable使用
/**
* 条件查询
*
* @param categoryId
* @return
*/
@GetMapping("/list")
@Cacheable(cacheNames = "userCache", key = "#categoryId")
@ApiOperation("根据分类id查询套餐")
public Result<List<Setmeal>> list(Long categoryId) {
Setmeal setmeal = new Setmeal();
setmeal.setCategoryId(categoryId);
setmeal.setStatus(StatusConstant.ENABLE);
//根据categoryId和状态查询
List<Setmeal> list = setmealService.list(setmeal);
return Result.success(list);
}
4、 @CacheEvict精确清理
/*添加套餐*/ @PostMapping @AutoFill(OperationType.INSERT)//公共字段自动填充 @CacheEvict(cacheNames = "userCache", key = "#setmeal.categoryId") public Result add(@RequestBody Setmeal setmeal){ //插入套餐数据 setmealService.add(setmeal); return Result.success(); }
5、@CacheEvict批量清理
/*修改售卖状态*/ @PostMapping("/status/{status}") @CacheEvict(cacheNames = "userCache", allEntries = true) public Result status(@PathVariable Integer status, Long id){ //修改数据 setmealService.updateStatus(status,id); return Result.success(); }