Redis模拟2分钟有效验证码


import redis.clients.jedis.Jedis;
import java.util.Random;
import java.util.Scanner;

/**
 * 手机验证码功能
 * 要求:
 * 1、输入手机号,点击发送后随机生成6位数字码,2分钟有效
 * 2、输入验证码,点击验证,返回成功或者失败
 * 3、每个手机号每天只能输入三次
 */
public class PhoneVerification {
    private static final Jedis jedis=new Jedis("192.168.111.130",6379);

    /**
     * 模拟验证码
     */
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        String phone =scanner.nextLong() + "";//用户输入的手机号
        PutYanZhengMa(phone);//验证码放进redis
        String usernum = scanner.nextLong() + "";//用户输入的验证码
        Verify(phone, usernum);//验证
    }

    /**
     * 验证是否正确
     */
    public static void Verify(String phone,String num){
        String codePhone="Verify"+phone+"code";//手机收验证码的key
        if (num.equals(jedis.get(codePhone))) {//正确
            System.out.println("成功");
        }
        else {
            System.out.println("失败");
        }
    }

    /**
     * 每个手机每天只能发三次,每个验证码120s==2分min有效时间
     * @param phone 手机号
     */
    public static void PutYanZhengMa(String phone){
        String codePhone="Verify"+phone+"code";//手机收验证码的key
        String codeTime="Verify"+phone+"count";//手机收验证码次数的key
        String count=jedis.get(codeTime);//该手机号今天获取验证码的次数
        if (count==null) {//没有就开始设置它的属性
            jedis.setex(codeTime,60*60*24,"1");
        }
        else if (Integer.parseInt(count)<=2){
            //已经有了,但没超,直接+1
            jedis.incr(codeTime);
        }
        else {
            System.out.println("已达三次了");
            return;
        }
        int nums= new Random().nextInt(1000000);//随机生成的6位数字验证码,
        jedis.setex(codePhone,120,nums+"");
        System.out.println("发送的验证码为"+nums+",2分钟后失效");
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

syf_wfl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值