Session short codes in the valid time

Session short codes in the valid time

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;
    }
}

Guess you like

Origin www.cnblogs.com/mozq/p/12001442.html