1.导入jar包
<!--redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!--springcache--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency>
2.配置application.yml文件(也可以不配置)
spring:
cache:
redis:
time-to-live: 1800000 #设置缓存有效期(毫秒)30分钟
这个配置会让缓存过30分钟自动失效
3.启动类上加注解
@EnableCaching //开启缓存注解功能
4.在相关的Contorller方法上加注解
1.查询方法
@Cacheable(value = "test", key = "#person.id")
@Cacheble注解表示这个方法有了缓存的功能,方法的返回值会被缓存下来,下一次调用该方法前,会去检查是否缓存中已经有值,如果有就直接返回,不调用方法。如果没有,就调用方法,然后把结果缓存起来。
value是指向该缓存的区域,key是该缓存的key值;
2.更新或删除方法
@CacheEvict(value = "test",key="#person.id") 清空指定缓存
@CacheEvict(value = "test",allEntries = true) 清空区域内全部缓存
@CacheEvict注解会清空指定缓存