栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

redis模拟手机验证码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

redis模拟手机验证码

package com.wss.springboot;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;


@SpringBootTest
public class PhoneCodeTest {
    @Autowired
    RedisTemplate redisTemplate;

    @Test
    void codeTest(){
        System.out.println("输入手机号");
        Scanner scan = new Scanner(System.in);
        String phone = scan.next();
        getPhoneAndSendCode(phone);
        System.out.println("输验证码");
        String code = scan.next();
        verifyCode(code);

    }
    //判读验证码输入是否正确
    public void verifyCode(String code){
        ValueOperations opsForValue = redisTemplate.opsForValue();
        String rsCode = opsForValue.get("codeKey");
        if (rsCode == null){
            System.out.println("验证码已失效");
        }
        if (code.equals(rsCode)){
            System.out.println("验证通过");
        }else {
            System.out.println("验证码错误");
        }
    }

    //判断手机发送次数,并生成验证码
    public void getPhoneAndSendCode(String phone){
        ValueOperations opsForValue = redisTemplate.opsForValue();
        String countKey = "countKey:"+phone;
        //获得手机发送次数  count
        String count = opsForValue.get(countKey);
        if (count == null){
            //count == null ,手机第一次发送,设置key value 和过期时间
            opsForValue.set(countKey, "1",24*60*60, TimeUnit.SECONDS);
        }else if (Integer.parseInt(count) <= 2){
            opsForValue.increment(countKey);
        }else{
            System.out.println("手机今天已发送三次验证码,无法再次发送");
            return;
        }
        //生成验证码
        String code = getCode();
        System.out.println("生成的验证码:"+code);
        //将验证码存储并设置过期时间
        opsForValue.set("codeKey", code, 30, TimeUnit.SECONDS);
    }

    //获得验证码
    public String getCode(){
        String code = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            int ran = random.nextInt(10);
            code += ran;
        }
        return code;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/361254.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号