SpringBoot Cache操作

在上一节JPA操作基础上修改

Cache缓存策略:使更少的操作数据库,更快的返回数据

1、引入cache依赖

1<dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-cache</artifactId> 4</dependency>

2.主要是修改UserSerViceImpl服务层实现类

1@Service 2@Transactional //事务 3public class UserServiceImpl implements UserService { 4 5 @Autowired 6 private UserRepository userRepository; 7 8 @Override 9 @Cacheable(value = "user", key = "#id") 10 public User findUserById(Integer id) { 11 System.out.println("查询用户查询数据库"); 12 return userRepository.getOne(id); 13 } 14 15 @Override 16 @Cacheable(value = "userListPage" , key = "#pageable") //key值可视化,每页的key值是不同的 17 public Page<User> findUserListPage(Pageable pageable) { 18 System.out.println("分页查询数据库"); 19 return userRepository.findAll(pageable); 20 } 21 @Override 22 //@CacheEvict(value = "users",key = "#id") //清空缓存中以users和key值缓存策略缓存的对象 23 @CacheEvict(value = "userListPage",allEntries = true) //清空所有缓存中以users缓存策略缓存的对象 24 public void saveUser(User user) { 25 userRepository.save(user); 26 } 27 28 /* 29 注解Caching可以混合几个注解 30 */ 31 @Override 32 @Caching(evict = {@CacheEvict(cacheNames = "user",key = "#user.id"), 33 @CacheEvict(cacheNames = "user2" ,key = "user2.id")}) 34 public void updateUser(User user) { 35 36 } 37 38}

3.测试TsetController类

1@Controller 2public class TestController { 3 4 @Autowired 5 private UserService userService; 6 7 @RequestMapping("/getUserById") 8 public @ResponseBody User getUserById(){ 9 System.out.println(userService.findUserById(1527)); 10 System.out.println(userService.findUserById(1527)); 11 System.out.println(userService.findUserById(1528)); 12 return userService.findUserById(1527); 13 } 14 15}

4.对启动类添加缓存注解

1@SpringBootApplication 2@EnableCaching //对缓存做配置 3public class DemoApplication { 4 5 public static void main(String[] args) { 6 SpringApplication.run(DemoApplication.class, args); 7 } 8 9}

5.进行测试:

运行结果:

第二次查询数据库是因为id不同没有这个缓存,会去查询数据库的

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

java将前端的json数组字符串转换为列表

记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )

SpringBoot Cache操作 - HelloWorld