SpringBoot 中 cache缓存的使用
1、pom.xml导入依赖 cache依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2、SpringBoot启动类上使用 @EnableCaching 注解
开启 cache 缓存应用
@EnableCaching
@SpringBootApplication
public class SpringbootMybaitsApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybaitsApplication.class, args);
}
}
3、在service 层中的方法上使用 cache 缓存相关注解
@Service
public class DepartService {
@Autowired
private DepartMapper departMapper;
@Cacheable(value = "dep",key = "#id")
public Department getDepartment(Integer id) throws SQLException {
System.out.println("执行了查询方法");
return departMapper.getDepartmentById(id);
}
@CachePut(value = "dep",key = "#department.id")
public Department updateDepartment(Department department){
System.out.println("执行了更新方法");
departMapper.updateDepartment(department);
return department;
}
@CacheEvict(value = "dep",key = "#id")
public String deleteDepartment(Integer id){
System.out.println("执行了删除方法");
departMapper.daleteDepartmentById(id);
return "success";
}
}
@Cacheable 注解
标注在查询方法上,开启缓存,方法执行之前会去缓存中查询数据,如果缓存中没有,才会执行方法查询数据。
-
value 指定缓存名。
-
key 指定缓存储存的key (缓存中数据储存是以 key-value 方式,value 储存方法返回的对象)。
@CachePut 注解
标注在更新方法上,用于更新缓存。
-
value 指定缓存名。
-
key 指定缓存更新的key (缓存中数据储存是以 key-value 方式,value 储存方法返回的对象)。
@CacheEvict 注解
标注在删除方法上,用于删除换成
-
value 指定缓存名。
-
key 指定缓存删除的key (缓存中数据储存是以 key-value 方式,value 储存方法返回的对象)。
@CacheConfig 注解
标注在类上,可以将缓存公共熟悉提取出来一起配置。(例如:将 前三个注解的 value 熟悉取出来使用 @CacheConfig(cacheNames = “dep”) 标注在类上)