Jedis案例-模拟验证码发送

Jedis案例-模拟验证码发送

package com.jedisDemo1;

import redis.clients.jedis.Jedis;


/**
 * @author Jacob
 * @create 2022-06-27 9:04
 */
public class VerificationCode {
    public static void main(String[] args) {
        //Verify("15120142316");
        getVericode("15155555", "585262");
    }

    //1.随机6位验证码
    public static String RamdomVericationCode() {
        //int value = (int) (Math.random() * (999999 - 100000 + 1) + 100000);//得到[a,b]闭区间的随机数
        String Verification = "";
        for (int i = 0; i < 6; i++) {
            int value = (int) (Math.random() * 10);//随机数0-1
            Verification += value;
        }
        return Verification;
    }

    //2.设置过期时间120s/expire key 用户每天只能申请3次验证码
    public static void Verify(String phone) {
        //计数的key和验证码key的规则拼接
        String countKey = "VericationCode" + phone + ":count";
        String verifyKey = "VericationCode" + phone + ":verify";
        //把key放入Reids中设置一条最多三次
        //连接redis
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        //根据key获取value
        String count = jedis.get(countKey);
        if (count == null) {
            //如果等于null说明还没有往redis中放入
            //设置键值的同是设置过期时间
            jedis.setex(countKey, 24 * 60 * 60, "1");
        } else if (Integer.parseInt(count) <= 2) {
            jedis.incr(countKey);//value增1
        } else if (Integer.parseInt(count) >= 3) {
            System.out.println("今日的发送次数已经超过3次!!");
            return;
        }

        //把验证码放入reids中
        //获取验证码
        String vcode = RamdomVericationCode();
        jedis.setex(verifyKey, 120, vcode);
        //关闭jedis
        jedis.close();

    }

    //3.校验验证码
    public static void getVericode(String phone, String code) {
        //连接jedis
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        String verifyKey = "VericationCode" + phone + ":verify";
        String codeKey = jedis.get(verifyKey);//根据形参phone拿对应的code

        if (codeKey.equals(code)) {
            System.out.println("成功!");
        } else {
            System.out.println("失败!");
        }

    }

}

打开这个方法获取验证码,获取验证码的时候打印栏没提示
在这里插入图片描述
Redis中查看获取的验证码(有效期2分钟)和验证次数(每天只能3次)

第一次,count是1,验证码083875

验证码校验
在这里插入图片描述

打开这个方法校验,正确则打印成功,错误则打印失败
在这里插入图片描述

在这里插入图片描述

一天不能超过3次验证码请求

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值