@Cacheable既作用在方法上,也就用在类上。当作用在方法上是只对该方法有用,作用在类上时,对该类的所有方法都有效。
示例:
controller:
@GetMapping("test_cache")
public String testCache(@RequestParam String flag){
String s = countryService.testCache(flag);
return s;
}
service:
String testCache(String flag);
serviceImpl:
@Override
@Cacheable(cacheNames = {"test.one.two"})
//@CachePut常用与更新操作; @CacheEvict常用删除操作;
public String testCache(String flag) {
log.info("flag={}",flag);
int timeCount = (int) (Math.random() * 1000);
log.info("timeCount={}",timeCount);
return String.valueOf(timeCount);
}
以 flag=a 为参数。连续调用两次controller中的接口,结果只打印出一次请求记录。
当换 flag=b 为参数时,控制台再次打印。但是,再执行一次就不再打印了。
说明相同的参数指指向一次就把结果缓存起来,等下次调用方法时,直接将所保存的缓存返回。