SpringBoot使用缓存
- SpringBoot来简单整合缓存,
- 项目,pom文件中加入spring-boot-starter-cache依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
<version>2.1.7.RELEASE</version>
</dependency>
- 实体类
@Data
public class User {
private Long id;
private String username;
private String password;
private Date createTime;
private Date updateTime;
}
- 启动类上加入@EnableCaching开启缓存
@SpringBootApplication
//开启缓存
@EnableCaching
public class SpringbootCacheApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootCacheApplication.class, args);
}
}
- 使用Controller做测试
/**
* @Description
* @Author
* @Version V1.0.0
* @Since 1.0
* @Date 2019-09-24
*/
@RestController
public class CacheUserController {
@Autowired
private UserService userService;
//http://localhost:8787/saveUser?id=2&username=关小羽
@ApiOperation(value = "数据缓存Cache", httpMethod = "GET")
@GetMapping("/saveUser")
@CachePut(value = "user" ,key = "#id")
public User saveUser(Long id,String username){
User user = new User();
user.setId(id);
user.setUsername(username);
userService.save(user);
return user;
}
//http://localhost:8787/queryUser?id=2
@GetMapping("/queryUser")
@Cacheable(value = "user" , key = "#id")
public User queryUser(Long id){
User user = userService.queryUser(id);
System.out.println (user);
return user;
}
//http://localhost:8787/deleteUser?id=2
@GetMapping("/deleteUser")
@CacheEvict(value = "user", key = "#id")
public String deleteUser(Long id){
userService.delete(id);
System.out.println ("success");
return "success";
}
//http://localhost:8787/deleteCache
@GetMapping("/deleteCache")
@CacheEvict(value = "user", allEntries = true)
public void deleteCache() {
}
}
转载:https://blog.csdn.net/weixin_43854141/article/details/101378484
查看评论