spring cache是一个框架,提供了关于缓存的开发注解;
spring cache提供了一层抽象,底层可以根据导入不同的依赖,切换不同的缓存的实现,具体就是通过CacheManager接口来统一不同的缓存技术;
spring cache 提供的cachemanager
EnCacheManager ---》 使用EnCache作为缓存技术
GuvavaCacheManager ---》使用GuvavaCache作为缓存技术
RedisCacheManager ---》使用Redis作为缓存技术
在spring boot 中使用缓存,只需要在启动类中加载@EnableCaching注解,并在pom.xml文件中导入对应缓存技术的坐标即可。
<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>
spring:
redis:
host: localhost
port: 3306
# password:
database: 0 #操作0号数据库
cache:
redis:
time-to-live: 1800000 #设置过期时间
spring cache 常用注解
@EnableCaching(启动类) 开启缓存注解功能
@Cacheable 在方法执行前检查缓存中是否有数据,如果有数据直接返回缓存数据;如果没有,调用方法并将方法放回值放到缓存中
@CachePut 将方法的返回值放到缓存中
@CacheEvict 将一条或多条数据从缓存中删除
@Resource
private CacheManager cacheManager;
@Resource
public EmployeeMapper employeeMapper;
@GetMapping("/g")
/*
@CachePut :将方法返回值,加入缓存
@CacheEvict : 删除一条或多条缓存数据
@Cacheable : 在方法执行前检查缓存中是否有数据,如果有数据直接返回缓存数据;如果没有,调用方法并将方法放回值放到缓存中
---------------------------------------------------------------------------------------------------
value 别名 cachename : 缓存分组
key : 缓存的key
condition : 缓存条件,满足指定条件,缓存数据
*/
@CachePut(value = "empCache",key = "#id")
@CacheEvict(value = "empCache",key = "#id")
@Cacheable(value = "empCache",key = "#id",condition = "#result != null")
public Employee selectById(Integer id){
Employee employee = employeeMapper.selectById(id);
return employee;
}