• Session中短信验证码设置有效时间


    Session中短信验证码设置有效时间

    package com.mozq.boot.kuayu01.controller;
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.servlet.http.HttpSession;
    import java.text.SimpleDateFormat;
    import java.util.*;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;
    
    /*
     问题:短信验证码过期清除策略,因为使用任务调度,无法取消先前的任务,前一次验证码定时任务会清除后面生成验证码。
     方案:验证码加时间戳的方式,清除前先判断时间戳是不是与该任务相同,不想同则说明验证码已经重新生成,此定时任务不应清除这个验证码。
     */
    @RestController
    public class SmsController {
        //创建线程池对象
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
    
        @RequestMapping("/sendSmsCheckCode")
        public String sendSmsCheckCode(HttpSession session){
            int code = (int) ((Math.random() + 1) * Math.pow(10, 5));
            String timeStamp = timeStamp();
    
            //添加时间戳
            Map<String, String> codeMap = new HashMap<>();
            codeMap.put("code", String.valueOf(code));
            codeMap.put("timestamp", timeStamp);
    
            session.setAttribute("code", codeMap);
            System.out.println(codeMap);
    
            //清除时根据时间戳判断是不是这个任务对应的验证码
            scheduledExecutorService.schedule(new Thread(()->{
                Map<String, String> codeMapS = (Map<String, String>) session.getAttribute("code");
                System.out.println(codeMapS);
                if(Objects.nonNull(codeMapS) && timeStamp.equals(codeMapS.get("timestamp"))){
                    session.removeAttribute("code");
                    System.out.println("清除session" + codeMapS);
                }
            }), 20, TimeUnit.SECONDS);
            return String.valueOf(code);
        }
    
        @RequestMapping("/check")
        public String check(HttpSession session){
            Integer code = (Integer) session.getAttribute("code");
            if(Objects.isNull(code)){
                System.out.println("验证码为空");
            }
            System.out.println(code);
            //使用一次之后,清除验证码
            session.removeAttribute("code");
            return String.valueOf(code);
        }
    
        public static String timeStamp(){
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").format(new Date());
            return format;
        }
    }
    
  • 相关阅读:
    【数论】 快速幂
    【时间复杂度】你还在担心时间复杂度太高吗?
    【数据结构】 最小生成树(三)——prim算法
    【数据结构】 最小生成树(二)——kruskal算法
    node.js初识11
    node.js初识10
    node.js初识09
    node.js初识08
    node.js初识07
    node.js初识06
  • 原文地址:https://www.cnblogs.com/mozq/p/12001442.html
Copyright © 2020-2023  润新知