当前位置:   article > 正文

缓存优化(redis)_redis time-to-live

redis time-to-live

目录

一、环境搭建

1、maven坐标

2、配置文件

二、缓存短信验证码

1、实现思路

2、代码改造

三、缓存菜品数据

1、实现思路

2、代码改造

四、SpringCache

1、介绍

 2、常用注解

 3、注解的使用:

 4、spring boot中使用spring cache

五、缓存套餐数据

1、实现思路

2、代码改造

2.1、导入坐标

2.2、配置文件

2.3、在启动类加入注解,开启缓存注解功能

2.4、在SetmealController控制类中加入缓存注解


一、环境搭建

1、maven坐标

  1. <!-- redis-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. </dependency>

2、配置文件

  1. spring:
  2. redis:
  3. host: localhost # 本地IP 或是 虚拟机IP
  4. port: 6379
  5. # password: root
  6. database: 0 # 默认使用 0号db
  7. cache:
  8. redis:
  9. time-to-live: 1800000 # 设置缓存数据的过期时间,30分钟

二、缓存短信验证码

1、实现思路

2、代码改造

  1. @RestController
  2. @RequestMapping("/user")
  3. @Slf4j
  4. public class UserController {
  5. @Autowired
  6. private UserService userService;
  7. @Autowired
  8. private StringRedisTemplate stringRedisTemplate;
  9. /**
  10. * 发送邮箱短信验证码
  11. * @param user
  12. * @return
  13. */
  14. @PostMapping("/sendMsg")
  15. public R<String> sendMsg(@RequestBody User user, HttpSession session){
  16. //获取邮箱
  17. String phone = user.getPhone();
  18. if(StringUtils.isNotEmpty(phone)){
  19. //发送验证码到邮箱
  20. String code = userService.send(user);
  21. //需要将生成的验证码保存到Session
  22. // session.setAttribute(phone,code);
  23. //将生成的验证码缓存到redis中,并且设置有效期为5分钟
  24. stringRedisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
  25. return R.success("手机验证码短信发送成功");
  26. }
  27. return R.error("短信发送失败");
  28. }
  29. /**
  30. * 移动端登录
  31. * @param map
  32. * @param session
  33. * @return
  34. */
  35. @PostMapping("/login")
  36. public R<User> sendMsg(@RequestBody Map map, HttpSession session){
  37. //获取邮箱
  38. String phone = map.get("phone").toString();
  39. //获取验证码
  40. String code = map.get("code").toString();
  41. //从Session中获取保存的验证码
  42. // Object codeInSession = session.getAttribute(phone);
  43. //从redis中获取缓存的验证码
  44. String s = stringRedisTemplate.opsForValue().get(phone);
  45. //进行验证码的比对(页面提交的验证码和Session中保存的验证码比对)
  46. if(s != null && s.equals(code)){
  47. //如果能够比对成功,说明登录成功
  48. LambdaQueryWrapper<User> eq = Wrappers.lambdaQuery(User.class)
  49. .eq(User::getPhone, phone);
  50. User user = userService.getOne(eq);
  51. if(user == null){
  52. //判断当前邮箱账号对应的用户是否为新用户,如果是新用户就自动完成注册
  53. user = new User();
  54. user.setPhone(phone);
  55. user.setStatus(1);
  56. userService.save(user);
  57. }
  58. session.setAttribute("user",user.getId());
  59. //如果用户登录成功,删除Redis中缓存的验证码
  60. stringRedisTemplate.delete(phone);
  61. return R.success(user);
  62. }
  63. return R.error("登录失败");
  64. }
  65. }

三、缓存菜品数据

1、实现思路

 

2、代码改造

  1. @RestController
  2. @Slf4j
  3. @RequestMapping("/dish")
  4. public class DishController {
  5. @Autowired
  6. private DishService dishService;
  7. @Autowired
  8. private DishFlavorService dishFlavorService;
  9. @Autowired
  10. private CategoryService categoryService;
  11. @Autowired
  12. private StringRedisTemplate stringRedisTemplate;
  13. @Autowired
  14. private RedisTemplate redisTemplate;
  15. /**
  16. * 分页查找
  17. * @param page
  18. * @param pageSize
  19. * @param name
  20. * @return
  21. */
  22. @GetMapping("/page")
  23. public R<Page> page(int page,int pageSize,String name){
  24. //构造分页对象
  25. Page<Dish> dishPage = new Page<>(page, pageSize);
  26. Page<DishDto> dishDtoPage = new Page<>();
  27. //条件构造器:过滤和排序
  28. LambdaQueryWrapper<Dish> like = Wrappers.lambdaQuery(Dish.class)
  29. .like(StringUtils.isNotEmpty(name),Dish::getName, name)
  30. .orderByDesc(Dish::getUpdateTime);
  31. //执行分页查询
  32. dishService.page(dishPage,like);
  33. //对象拷贝:将第一个参数对象,拷贝到第二个参数的对象中,第三个参数表示忽略拷贝的内容
  34. BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
  35. List<Dish> records = dishPage.getRecords();
  36. List<DishDto> list = records.stream().map((item) -> {
  37. DishDto dishDto = new DishDto();
  38. BeanUtils.copyProperties(item,dishDto);
  39. Long categoryId = item.getCategoryId(); //分类id
  40. //根据id查询分类对象
  41. Category byId = categoryService.getById(categoryId);
  42. if(byId != null){
  43. String byIdName = byId.getName();
  44. dishDto.setCategoryName(byIdName);
  45. }
  46. return dishDto;
  47. }).collect(Collectors.toList());
  48. dishDtoPage.setRecords(list);
  49. return R.success(dishDtoPage);
  50. }
  51. /**
  52. * 新增菜品
  53. * @param dishDto
  54. * @return
  55. */
  56. @PostMapping
  57. public R<String> save(@RequestBody DishDto dishDto){
  58. dishService.saveWithFlavor(dishDto);
  59. //清理所有菜品的缓存数据
  60. // Set<String> keys = stringRedisTemplate.keys("dish_*");
  61. // stringRedisTemplate.delete(keys);
  62. //清理某个分类下面的菜品缓存数据
  63. String key = "dish_" + dishDto.getCategoryId() + "_1";
  64. stringRedisTemplate.delete(key);
  65. return R.success("新增菜品成功");
  66. }
  67. /**
  68. * 根据id查询菜品信息和对应的口味信息
  69. * @param id
  70. * @return
  71. */
  72. @GetMapping("/{id}")
  73. public R<DishDto> get(@PathVariable Long id){
  74. DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);
  75. return R.success(byIdWithFlavor);
  76. }
  77. /**
  78. * 修改菜品
  79. * @return
  80. */
  81. @PutMapping
  82. public R<String> update(@RequestBody DishDto dishDto){
  83. dishService.updateWithFlavor(dishDto);
  84. //清理某个分类下面的菜品缓存数据
  85. String key = "dish_" + dishDto.getCategoryId() + "_1";
  86. stringRedisTemplate.delete(key);
  87. return R.success("修改菜品成功");
  88. }
  89. /**
  90. * 根据条件查询对应的菜品数据
  91. * @param dish
  92. * @return
  93. */
  94. @GetMapping("list")
  95. public R<List<DishDto>> list(Dish dish){
  96. List<DishDto> collect = null;
  97. //dish_1397844391040167938_1(动态构造key)
  98. String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
  99. //先从redis中获取缓存数据
  100. collect = JSON.parseArray(stringRedisTemplate.opsForValue().get(key), DishDto.class);
  101. if(collect != null){
  102. //如果存在,直接返回,无需查询数据库
  103. return R.success(collect);
  104. }
  105. //构造查询条件,并添加排序条件,再查询状态为1(起售状态)的菜品
  106. LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = Wrappers.lambdaQuery(Dish.class)
  107. .eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
  108. .eq(Dish::getStatus,1)
  109. .orderByAsc(Dish::getSort)
  110. .orderByDesc(Dish::getUpdateTime);
  111. List<Dish> list = dishService.list(dishLambdaQueryWrapper);
  112. collect = list.stream().map((item) -> {
  113. DishDto dishDto = new DishDto();
  114. BeanUtils.copyProperties(item, dishDto);
  115. Long categoryId = item.getCategoryId(); //分类id
  116. //根据id查询分类对象
  117. Category byId = categoryService.getById(categoryId);
  118. if (byId != null) {
  119. String byIdName = byId.getName();
  120. dishDto.setCategoryName(byIdName);
  121. }
  122. //当前菜品的id
  123. Long dishId = item.getId();
  124. //获取当前菜品口味
  125. LambdaQueryWrapper<DishFlavor> eq = Wrappers.lambdaQuery(DishFlavor.class)
  126. .eq(DishFlavor::getDishId, dishId);
  127. List<DishFlavor> dishFlavorsList = dishFlavorService.list(eq);
  128. dishDto.setFlavors(dishFlavorsList);
  129. return dishDto;
  130. }).collect(Collectors.toList());
  131. //如果不存在,需要查询数据库,将查询到的菜品数据缓存到Redis
  132. stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(collect),60, TimeUnit.MINUTES);
  133. return R.success(collect);
  134. }
  135. /**
  136. * 菜品起售停售功能 status:0 停售 1 起售
  137. * @param ids
  138. * @return
  139. */
  140. @PostMapping("/status/{status}")
  141. public R<String> status(@PathVariable int status,@RequestParam List<Long> ids){
  142. ids.stream().forEach((item) -> {
  143. LambdaUpdateWrapper<Dish> set = Wrappers.lambdaUpdate(Dish.class)
  144. .eq(item != null, Dish::getId, item);
  145. if(status == 0){
  146. set.ne(Dish::getStatus,0).set(Dish::getStatus, 0);
  147. dishService.update(set);
  148. }else{
  149. set.ne(Dish::getStatus,1).set(Dish::getStatus, 1);
  150. dishService.update(set);
  151. }
  152. Dish byId = dishService.getById(item);
  153. //清理某个分类下面的菜品缓存数据
  154. String key = "dish_" + byId.getCategoryId() + "_1";
  155. if(stringRedisTemplate.opsForValue().get(key) != null) {
  156. stringRedisTemplate.delete(key);
  157. }
  158. });
  159. return R.success("菜品已更改为停售");
  160. }
  161. /**
  162. * 菜品删除
  163. * @param ids
  164. * @return
  165. */
  166. @DeleteMapping
  167. public R<String> delete(@RequestParam List<Long> ids){
  168. ids.stream().forEach((item) -> {
  169. Dish byId = dishService.getById(item);
  170. //清理某个分类下面的菜品缓存数据
  171. String key = "dish_" + byId.getCategoryId() + "_1";
  172. if(stringRedisTemplate.opsForValue().get(key) != null) {
  173. stringRedisTemplate.delete(key);
  174. }
  175. dishService.removeById(item);
  176. });
  177. return R.success("删除菜品成功");
  178. }
  179. }

四、SpringCache

1、介绍

 2、常用注解

 3、注解的使用:

 

 ​​​​​​​

 

 4、spring boot中使用spring cache

 

五、缓存套餐数据

1、实现思路

 

2、代码改造

2.1、导入坐标

  1. <!-- redis-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-cache</artifactId>
  9. <version>2.7.3</version>
  10. </dependency>

2.2、配置文件

  1. spring
  2. redis:
  3. host: localhost # 本地IP 或是 虚拟机IP
  4. port: 6379
  5. # password: root
  6. database: 0 # 默认使用 0号db
  7. cache:
  8. redis:
  9. time-to-live: 1800000 # 设置缓存数据的过期时间,30分钟

2.3、在启动类加入注解,开启缓存注解功能

  1. @SpringBootApplication
  2. @ServletComponentScan
  3. @EnableTransactionManagement
  4. @MapperScan(basePackages = "com.itheima.reggie.mapper")
  5. @EnableCaching //开启缓存注解
  6. public class ReggieApplication {
  7. public static void main(String[] args) {
  8. SpringApplication.run(ReggieApplication.class, args);
  9. }
  10. }

2.4、在SetmealController控制类中加入缓存注解

  1. /**
  2. * 套餐管理
  3. */
  4. @Slf4j
  5. @RestController
  6. @RequestMapping("/setmeal")
  7. public class SetmealController {
  8. @Autowired
  9. private SetmealService setmealService;
  10. @Autowired
  11. private SetmealDishService setmealDishService;
  12. @Autowired
  13. private CategoryService categoryService;
  14. /**
  15. * 套餐分页查询
  16. * @param page
  17. * @param pageSize
  18. * @param name
  19. * @return
  20. */
  21. @GetMapping("/page")
  22. public R<Page> page(int page, int pageSize, String name){
  23. //构造分页对象
  24. Page<Setmeal> setmealPage = new Page<>(page, pageSize);
  25. Page<SetmealDto> SetmealDtoPage = new Page<>();
  26. //条件构造器:过滤和排序
  27. LambdaQueryWrapper<Setmeal> like = Wrappers.lambdaQuery(Setmeal.class)
  28. .like(StringUtils.isNotEmpty(name),Setmeal::getName, name)
  29. .orderByDesc(Setmeal::getUpdateTime);
  30. //执行分页查询
  31. setmealService.page(setmealPage,like);
  32. //对象拷贝:将第一个参数对象,拷贝到第二个参数的对象中,第三个参数表示忽略拷贝的内容
  33. BeanUtils.copyProperties(setmealPage,SetmealDtoPage,"records");
  34. List<Setmeal> records = setmealPage.getRecords();
  35. List<SetmealDto> list = records.stream().map((item) -> {
  36. SetmealDto setmealDto = new SetmealDto();
  37. BeanUtils.copyProperties(item,setmealDto);
  38. Long categoryId = item.getCategoryId(); //分类id
  39. //根据id查询分类对象
  40. Category byId = categoryService.getById(categoryId);
  41. if(byId != null){
  42. String byIdName = byId.getName();
  43. setmealDto.setCategoryName(byIdName);
  44. }
  45. return setmealDto;
  46. }).collect(Collectors.toList());
  47. SetmealDtoPage.setRecords(list);
  48. return R.success(SetmealDtoPage);
  49. }
  50. /**
  51. * 新增套餐
  52. * @param setmealDto
  53. * @return
  54. */
  55. @CacheEvict(value = "setmealCache",allEntries = true)
  56. @PostMapping
  57. public R<String> save(@RequestBody SetmealDto setmealDto){
  58. setmealService.saveWithDish(setmealDto);
  59. return R.success("新增套餐成功");
  60. }
  61. /**
  62. * 根据条件查询套餐数据
  63. * @return
  64. */
  65. @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
  66. @GetMapping("list")
  67. public R<List<Setmeal>> list(Setmeal setmeal){
  68. LambdaQueryWrapper<Setmeal> eq = Wrappers.lambdaQuery(Setmeal.class)
  69. .eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId())
  70. .eq(setmeal.getStatus() != null,Setmeal::getStatus, setmeal.getStatus())
  71. .orderByDesc(Setmeal::getUpdateTime);
  72. List<Setmeal> list = setmealService.list(eq);
  73. return R.success(list);
  74. }
  75. /**
  76. * 删除套餐
  77. * @param ids
  78. * @return
  79. */
  80. //allENtries = true表示删除全部
  81. @CacheEvict(value = "setmealCache",allEntries = true)
  82. @DeleteMapping
  83. public R<String> delete(@RequestParam List<Long> ids){
  84. setmealService.removeWithDish(ids);
  85. return R.success("套餐数据删除成功");
  86. }
  87. /**
  88. * 套餐起售停售功能 status:0 停售 1 起售
  89. * @param ids
  90. * @return
  91. */
  92. @CacheEvict(value = "setmealCache",allEntries = true)
  93. @PostMapping("/status/{status}")
  94. public R<String> status(@PathVariable int status,@RequestParam List<Long> ids){
  95. ids.stream().forEach((item) -> {
  96. LambdaUpdateWrapper<Setmeal> set = Wrappers.lambdaUpdate(Setmeal.class)
  97. .eq(item != null, Setmeal::getId, item);
  98. if(status == 0){
  99. set.ne(Setmeal::getStatus,0).set(Setmeal::getStatus, 0);
  100. setmealService.update(set);
  101. }else{
  102. set.ne(Setmeal::getStatus,1).set(Setmeal::getStatus, 1);
  103. setmealService.update(set);
  104. }
  105. });
  106. return R.success("菜品已更改为停售");
  107. }
  108. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/466883
推荐阅读
相关标签
  

闽ICP备14008679号