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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM