一、依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
二、使用
@Cacheable:执行前缓存注解
key | 缓存数据的key,该key和缓存结果组成cache缓存数据 |
value/cacheNames | cache缓存的Key |
keyGenerator | key生成器,指定对应ID,key和keyGenerator二选一 |
cacheManager | 缓存管理器,指定对应ID |
cacheResolver | 缓存解析器,指定对应ID |
condition | 该值为表达式,表示符合条件才进行缓存 |
unless | 同上相反,符合条件就不进行缓存 |
sync | 是否使用异步模式 |
@CachePut:执行后缓存注解
该注解比@Cacheable注解少一个sync属性,其余完全一致 |
@CacheEvict:缓存清除注解
该注解比@Cacheable注解少两个属性unless和sync,但也多两个属性 | |
allEntries | true表示删除所有缓存,false表示按key删除指定缓存 |
beforeInvocation | true和false,是否在方法之前执行 |
@CacheConfig:统一注解(该注解用在类上,定义了该类中所有缓存注解公共值)
cacheNames | 同上 |
keyGenerator | |
cacheManager | |
cacheResolver |
@Caching:复合注解
cacheable | @Cacheable注解数组 |
put | @CachePut注解数组 |
evict | @CacheEvict注解数组 |
@Caching(
cacheable = {
@Cacheable(cacheNames = "cacheableName")
},
put = {
@CachePut(cacheNames = "cachePutName")
}
)
public Employee getEmployeeById(int id){
System.out.println("bmp------查询" + id + "号员工------");
return employeeMapper.getEmployeeById(id);
}
三、实例
@ResponseBody
@Controller
public class EmployeeController {
@Autowired
EmployeeService employeeService;
@RequestMapping("/amp/{id}")
public Employee getEmployee1(@PathVariable("id") int id){
return employeeService.getAmpById(id);
}
@RequestMapping("/bmp/{id}")
public Employee getEmployee2(@PathVariable("id") int id){
return employeeService.getBmpById(id);
}
@RequestMapping("/delAmp")
public void getEmployee99(){
employeeService.delectAmp();
}
}
@CacheConfig(keyGenerator = "myKeyGenerator")
@Service
public class EmployeeService {
@Autowired
EmployeeMapper employeeMapper;
@Cacheable(cacheNames = "amp")
public Employee getAmpById(int id){
System.out.println("amp------查询" + id + "号员工------");
return employeeMapper.getEmployeeById(id);
}
@CachePut(cacheNames = "bmp")
public Employee getBmpById(int id){
System.out.println("bmp------查询" + id + "号员工------");
return employeeMapper.getEmployeeById(id);
}
@CacheEvict(cacheNames = "amp", allEntries = true)
public void delectAmp(){
System.out.println("删除所有缓存");
}
}
@Configuration
public class EmpKeyGenerator{
@Bean("myKeyGenerator")
public KeyGenerator getKeyGenerator(){
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, Object... objects) {
return method.getName() + "_" + Arrays.asList(objects).get(0);
}
};
}
}
四、个人理解
就个人而言是把缓存理解为一个Map<String, Map<String, Object>>类似数据的,把cacheNames看成第一层的Key值,而Key则是第二层的Key,这个Key指向的数据才是需要存储的数据
以下面RedisCacheManager为例
存储缓存数据的是ConcurrentMap类型数据,而value值是RedisCache类型
该类型有一个RedisCacheWriter属性根据name(第一个Key)、Key(第二个Key)、cacheValue(需要缓存的数据)和失效时间来存储缓存数据