学习目标:
提示:学习如何利用Redis来实现发送验证码功能
学习产出:
流程图
1. 准备pom环境
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope><version>5.1.47</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.3</version></dependency><!--hutool--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.7.17</version></dependency>
2. 配置ThreadLocal和过滤器
public class UserHolder {private static final ThreadLocal<UserDTO> tl = new ThreadLocal<>();public static void saveUser(UserDTO user){tl.set(user);}public static UserDTO getUser(){return tl.get();}public static void removeUser(){tl.remove();}
}
@Configuration
public class MvcConfig implements WebMvcConfigurer {@Autowiredprivate StringRedisTemplate redis;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new LoginInterceptor(redis))//哪些请求放行不走过滤器.excludePathPatterns("/user/code","/user/login","/blog/hot","/shop/**","/shop-type/**","/voucher/**");}
}
---------------------------------------------
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {private StringRedisTemplate redis;public LoginInterceptor(StringRedisTemplate redis) {this.redis = redis;}//controller执行之前@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {//1.获取请求头中的tokenString authorization = request.getHeader("authorization");if (StrUtil.isBlank(authorization)) {response.setStatus(401);return false;}//2.基于token获取Redis中的用户Map<Object, Object> userMap = redis.opsForHash().entries("login:token:" + authorization);//3.判断用户是否存在if (userMap.isEmpty()) {//4.不存在,拦截,401response.setStatus(401);return false;}//5.将查询到的Hash数据转换为Dto对象UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);//6.存在,保存信息到ThreadLocalUserHolder.saveUser(userDTO);//7.访问接口每次都会刷新token过期时间redis.expire("login:token:" + authorization,30,TimeUnit.MINUTES);//7.放行return true;}//渲染后返回给前台数据前@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {//移除用户,避免内存泄露UserHolder.removeUser();}
}
3. Controller层:负责接收请求和向下分配
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {@Resourceprivate IUserService userService;/*** 发送手机验证码*/@PostMapping("code")public Result sendCode(@RequestParam("phone") String phone) {//调用Service层来实现具体逻辑return userService.sendCode(phone);}}
4. Service层:负责业务的处理逻辑
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {private static final ObjectMapper mapper = new ObjectMapper();@Resourceprivate StringRedisTemplate redis;@Overridepublic Result sendCode(String phone) {//1.校验手机号if (RegexUtils.isPhoneInvalid(phone)) {//2.如果不符合,返回错误信息return Result.fail("无效手机号");}//3.符合,生成验证码String code = RandomUtil.randomNumbers(6);//4.保存验证码到Redis中redis.opsForValue().set(USER_NICK_NAME_PREFIX + phone, code, 60, TimeUnit.SECONDS);//5.模拟发送验证码log.info("发送验证码为===> {}", code);//6.返回return Result.ok();}//通过手机号创建新用户private User createUserWithPhone(String phone) {//创建用户User user = new User();user.setPhone(phone);user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));save(user);return user;}
}