1. 程式人生 > 其它 >Java Redis傳送簡訊驗證碼

Java Redis傳送簡訊驗證碼

package com.redis.demo;
 
import redis.clients.jedis.Jedis;
 
import java.util.Random;
 
public class PhoneCode {
    public static void main(String[] args) {
      // 模擬驗證碼傳送
        verifyCode("13899996666");
    }
 
    // 3.驗證碼校驗
    public static void getRedisCode(String phone, String code) {
        
// 連線redis www.dianjilingqu.com Jedis jedis = new Jedis("127.0.0.1", 6379); // 驗證碼key String codeKey = "VerifyCode" + phone + ":code"; // Redis中驗證碼 String redisCode = jedis.get(codeKey); // 判斷 if (redisCode.equals(code)) { System.out.println("
成功"); } else { System.out.println("失敗"); } jedis.close(); } // 2.每個手機每天只能傳送3次,驗證碼放到redis中,設定過期時間 public static void verifyCode(String phone) { // 連線redis Jedis jedis = new Jedis("127.0.0.1", 6379); // 手機發送次數key String countKey = "
VerifyCode" + phone + ":count"; // 驗證碼key String codeKey = "VerifyCode" + phone + ":code"; String count = jedis.get(countKey); System.out.println(count); if (count == null) { // 第一次傳送,設定傳送次數為1 jedis.setex(countKey, 24*60*60, "1"); } else if(Integer.parseInt(count) <= 2) { // 傳送次數加1 jedis.incr(countKey); } else if(Integer.parseInt(count) > 3){ System.out.println("今天的傳送次數已經超過3次"); jedis.close(); } // 1.傳送驗證碼放到redis www.dianjilingqu.com String vcode = getCode(); jedis.setex(codeKey, 120, vcode); String s = jedis.get(codeKey); System.out.println(s); jedis.close(); } // 生成6位數字驗證碼 public static String getCode() { Random random = new Random(); String code = ""; for (int i = 0; i < 6; i++) { int rand = random.nextInt(10); code += rand; } return code; } }