springboot 缓存 20
本文将介绍springboot缓存。
1、环境约束
- win10 64位操作系统
- idea2018.1.5
- maven-3.0.5
- jdk-8u162-windows-x64
2、前提约束
- 完成springboot整合jpa https://www.jianshu.com/p/d1fadd9af674
注意,作者使用的springboot版本是2.1.8.RELEASE
3、操作步骤
- 在主启动类上开启缓存开关
@EnableCaching
在主启动类同级目录下创建一个CacheController.java
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
public class CacheController{
@Resource
UserDao userDao;
@GetMapping("/query")
@Cacheable(value = "user", key = "#id")
//方法中使用到了@Cacheable注解,这个注解在执行前先查看缓存中是不是已经存在了,
//如果存在,直接返回。如果不存在,将方法的返回值放入缓存。
public User query(int id) {
return userDao.findById(id).get();
}
@GetMapping("/insert")
@CachePut(value = "user", key = "#id", condition = "#id % 2 == 1")
//方法中使用到了@CachePut注解,这个注解直接将返回值放入缓存中,通常用于保存和修改方法中
public void insert(User user) {
userDao.save(user);
}
@GetMapping("/delete")
@CacheEvict(value = "user", key = "#id")
//方法中使用到了@CacheEvict注解,这个注解在执行方法执行成功后会从缓存中移除
public String deleteHouse(Integer id) {
userDao.deleteById(id);
return "success";
}
}
- 修改application.properties,增加日志打印配置:
spring.jpa.show-sql=true
- 启动,测试,假设启动端口为8080,访问 http://localhost:8080/query?id=1 两次,第一次执行日志打印sql,第二次就没有打印sql,说明第2次没有去查询数据库,缓存起了作用。