1.启动类标明@EnableCaching
@SpringBootApplication
@MapperScan("com.jx.luckyDraw.mapper")
@EnableCaching
public class LuckyDrawApplication {
public static void main(String[] args) {
SpringApplication.run(LuckyDrawApplication.class, args);
}
}
2.常用注解的种类
@Cacheable
@CachePut
@CacheEvict
2.1 作用
@Cacheable:在方法执行前判断对应缓存是否存在,如果存在直接返回缓存结果,否者执行方法将结果缓存,适用于查询类。
@CachePut:与@Cacheable不同的是@CachePut一定会执行方法,并将方法的返回值更新到缓存,适用于更新,插入。
@CacheEvict:清除缓存。
2.2 例子
@Cacheable
@Cacheable(cacheNames = "drawDetails", key = "#userId + ':' + #batchId", unless = "#result ==null")
public DrawDetailPO getDrawDetails(String userId, Long batchId) {
当getDrawDetails方法的返回值不为null时,将方法的执行结果按照#userId + ‘:’ + #batchId 的方式缓存到redis中。
redis中键名为:
drawDetails::81466011bd2a7cf40502a08827038390:1490935513660657664
@CacheEvict
@CacheEvict(value = {"drawBatch", "drawDetails"}, allEntries = true, condition = "#result > 0")
@Override
public int newDrawBatchInfo(Integer batchCount) {
当newDrawBatchInfo方法的返回值大于0时,将命名空间为drawBatch" 或者drawDetails的键全部删除。
allEntries 默认为false,当有多个键时必须配置true才能删除。
在这种没指定key,使用默认keyGenerator 时,必须使用allEntries =true才能删除
@Cacheable(cacheNames = "employeeSelectList", unless = "#result ==null")
public List<HrmEmployeeSelectVO> querySelectList(HrmEmployeeSelectVO employeeSelectVO) {
return employeeMapper.querySelectList(employeeSelectVO);
}
@CacheEvict(value = "employeeSelectList",allEntries = true,condition = "#result = true ")
beforeInvocation 属性:是否在方法执行前删除,默认为false。