1.@EnableCaching
在springBoot启动类上开启缓存
@SpringBootApplication
@ComponentScan("com.example.**")
@EnableJpaRepositories
@EnableCaching
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
2.@Cacheable 访问方法进行缓存
这里使用sleep延时方法返回,当第二次调用该方法时会立即返回信息,不会去执行方法体内容
@cacheable中的值为缓存的key
@GetMapping("/cach1")
@Cacheable("cach")
public String springCache() throws InterruptedException {
Thread.sleep(4000);
return "cache1";
}
3.@CacheEvict 修改缓存信息
当调用修改方法后会立即更新cach的缓存
@GetMapping("/cach2")
@CacheEvict("cach")
public String springCacheChange(){
return "cache2";
}