Redis实现简单的验证码功能(简单)

Redis的简单验证码

此次代码仅适合初学者进行学习Redis,能够初步的掌握Redis在ideal中的基本操作,代码简单易懂

原理

  1. 生成随机的验证码。可以通过java的Random随机函数进行产生
  2. 建立函数生成key ,设置Redis设置过期时间,并将key值与验证码写入到Redis中
  3. 读取生成的验证进行校验

代码实现

创建maven项目 配置pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>redisTest</artifactId>
    <version>1.0-SNAPSHOT</version>
<dependencies>
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>3.2.0</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>compile</scope>
    </dependency>
</dependencies>
</project>
  1. 生成随机的六位数验证码
 //生成随机的六位数
    public  static  String getCode(){
        Random random = new Random();
        String code="";
        for(int i=0;i<6;i++){
            //生成10以内的10位数随机整数
            int rand = random.nextInt(10);
           //拼接随机数
            code+=rand;
        }
        return  code ;
    }
  1. 将验证码写入到Redis中,并设定过期时间(2分钟),每天只能生成三次验证码
 public static void verifyCode(String Phone){
        Jedis jedis = new Jedis("niit02", 7001);
        String  CountKey="verify"+Phone+":count";
        String  CodeKey="verify"+Phone+":code";
        String count = jedis.get(CodeKey);
        if(count==null){
            jedis.setex(CountKey,24*60*60,"1");

        }else if(Integer.parseInt(count)<=2){
            jedis.incr(CountKey);
        }else if (Integer.parseInt(count)>2) {
            System.out.println("三次机会已经用完");
            jedis.close();
        }
        String code = getCode();
        jedis.setex(CodeKey,120,code);
        jedis.close();
    }
  1. 验证手机号和验证码
 ///验证,手机号与验证码
    public static void getRdisCode (String Phone,String Code){
        Jedis jedis = new Jedis("niit02", 7001);
        String  CodeKey="verify"+Phone+":code";
        String redisCode = jedis.get(CodeKey);
        System.out.println(redisCode);
        if(redisCode.equals(Code)){
            System.out.println("成功");
        }else {
            System.out.println("失败");
        }
       jedis.close();
    }
  1. 主函数调用
 public static void main(String[] args) {
//verifyCode("15182021426");

getRdisCode("15182021426","756430");
    }
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值