当前位置:   article > 正文

Spring Boot 笔记 020 redis集成

Spring Boot 笔记 020 redis集成

1.1 安装redis

Windows 下 Redis 安装与配置 教程_redis windows-CSDN博客

2.1 引入redis坐标

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

2.2 配置redis信息

2.3 使用redis

2.3.1 在controller登录接口中设置值,在更改密码中删除值

  1. package com.geji.controller;
  2. import com.geji.pojo.Result;
  3. import com.geji.pojo.User;
  4. import com.geji.service.UserService;
  5. import com.geji.utils.JwtUtil;
  6. import com.geji.utils.Md5Util;
  7. import com.geji.utils.ThreadLocalUtil;
  8. import jakarta.validation.constraints.Pattern;
  9. import org.hibernate.validator.constraints.URL;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.data.redis.core.StringRedisTemplate;
  12. import org.springframework.data.redis.core.ValueOperations;
  13. import org.springframework.util.StringUtils;
  14. import org.springframework.validation.annotation.Validated;
  15. import org.springframework.web.bind.annotation.*;
  16. import java.util.HashMap;
  17. import java.util.Map;
  18. import java.util.concurrent.TimeUnit;
  19. @RestController
  20. @RequestMapping("/user")
  21. @Validated
  22. public class UserController {
  23. @Autowired
  24. private UserService userService;
  25. @Autowired
  26. private StringRedisTemplate stringRedisTemplate;
  27. @PostMapping("/register")
  28. public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
  29. //查询用户
  30. User u = userService.findByUserName(username);
  31. if (u == null) {
  32. //没有占用
  33. //注册
  34. userService.register(username, password);
  35. return Result.success();
  36. } else {
  37. //占用
  38. return Result.error("用户名已被占用");
  39. }
  40. }
  41. @PostMapping("/login")
  42. public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
  43. //根据用户名查询用户
  44. User loginUser = userService.findByUserName(username);
  45. //判断该用户是否存在
  46. if (loginUser == null) {
  47. return Result.error("用户名错误");
  48. }
  49. //判断密码是否正确 loginUser对象中的password是密文
  50. if (Md5Util.getMD5String(password).equals(loginUser.getPassword())) {
  51. //登录成功
  52. Map<String, Object> claims = new HashMap<>();
  53. claims.put("id", loginUser.getId());
  54. claims.put("username", loginUser.getUsername());
  55. String token = JwtUtil.genToken(claims);
  56. //把token存储到redis中
  57. ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
  58. operations.set(token,token,1, TimeUnit.HOURS);
  59. return Result.success(token);
  60. }
  61. return Result.error("密码错误");
  62. }
  63. @GetMapping("/userInfo")
  64. public Result<User> userInfo() {
  65. Map<String, Object> map = ThreadLocalUtil.get();
  66. String username = (String) map.get("username");
  67. User user = userService.findByUserName(username);
  68. return Result.success(user);
  69. }
  70. @PutMapping("/update")
  71. public Result update(@RequestBody @Validated User user) {
  72. userService.update(user);
  73. return Result.success();
  74. }
  75. @PatchMapping("updateAvatar")
  76. public Result updateAvatar(@RequestParam @URL String avatarUrl) {
  77. userService.updateAvatar(avatarUrl);
  78. return Result.success();
  79. }
  80. @PatchMapping("/updatePwd")
  81. public Result updatePwd(@RequestBody Map<String, String> params,@RequestHeader("Authorization") String token) {
  82. //1.校验参数
  83. String oldPwd = params.get("old_pwd");
  84. String newPwd = params.get("new_pwd");
  85. String rePwd = params.get("re_pwd");
  86. if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
  87. return Result.error("缺少必要的参数");
  88. }
  89. //原密码是否正确
  90. //调用userService根据用户名拿到原密码,再和old_pwd比对
  91. Map<String,Object> map = ThreadLocalUtil.get();
  92. String username = (String) map.get("username");
  93. User loginUser = userService.findByUserName(username);
  94. if (!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))){
  95. return Result.error("原密码填写不正确");
  96. }
  97. //newPwd和rePwd是否一样
  98. if (!rePwd.equals(newPwd)){
  99. return Result.error("两次填写的新密码不一样");
  100. }
  101. //2.调用service完成密码更新
  102. userService.updatePwd(newPwd);
  103. //删除redis中对应的token
  104. ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
  105. operations.getOperations().delete(token);
  106. return Result.success();
  107. }
  108. }

2.3.2 在拦截器中获取值,和用户携带的值对比,如果不存在就拦截

  1. package com.geji.interceptors;
  2. import com.geji.pojo.Result;
  3. import com.geji.utils.JwtUtil;
  4. import com.geji.utils.ThreadLocalUtil;
  5. import jakarta.servlet.http.HttpServletRequest;
  6. import jakarta.servlet.http.HttpServletResponse;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.data.redis.core.StringRedisTemplate;
  9. import org.springframework.data.redis.core.ValueOperations;
  10. import org.springframework.stereotype.Component;
  11. import org.springframework.web.servlet.HandlerInterceptor;
  12. import java.util.Map;
  13. @Component
  14. public class LoginInterceptor implements HandlerInterceptor {
  15. @Autowired
  16. private StringRedisTemplate stringRedisTemplate;
  17. @Override
  18. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  19. //令牌验证
  20. String token = request.getHeader("Authorization");
  21. //验证token
  22. try{
  23. //从redis中获取相同的token
  24. ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
  25. String redisToken = operations.get(token);
  26. if (redisToken==null){
  27. //token已经失效了
  28. throw new RuntimeException();
  29. }
  30. Map<String,Object> claims= JwtUtil.parseToken(token);
  31. //把业务数据存储到ThreadLocal中
  32. ThreadLocalUtil.set(claims);
  33. return true;
  34. }catch (Exception e){
  35. response.setStatus(401);
  36. return false;
  37. }
  38. }
  39. @Override
  40. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  41. //清空ThreadLocal中的数据
  42. ThreadLocalUtil.remove();
  43. }
  44. }

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

闽ICP备14008679号