把短信验证码存储在redis

校验短信验证码

接着上一篇博客https://blog.csdn.net/qq_42981638/article/details/94656441,成功实现可以发送短信验证码之后,一般可以把验证码存放在redis中,并且设置存放时间,一般短信验证码都是1分钟或者90s过期,这个看个人需求。所以我们可以利用redis的特性,设置存放时间,直接上代码。
第一步,在pom文件导入redis的依赖

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.1.0</version>
</dependency>

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.3.2</version>
</dependency>

第二步,在配置文件中配置好,redis的端口号,密码

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=root
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=5000

**接着上代码
在这里插入图片描述

package com.koohe.util;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

/** 短信发送工具类 */
public class SmsSendUtil {
    /** 产品名称:云通信短信API产品,开发者无需替换 */
    private static final String PRODUCT = "Dysmsapi";
    /** 产品域名,开发者无需替换 */
    private static final String DOMAIN = "dysmsapi.aliyuncs.com";
    // 签名KEY
    private static final String ACCESS_KEY_ID = "LTAIiKVKFzm3Vsri";
    // 签名密钥
    private static final String ACCESS_KEY_SECRET = "ww9nVlltvqfhjSWscfoVq04M7aItPY";
    // 短信模板ID: SMS_11480310
    private static final String TEMPLATE_CODE = "SMS_11480310";
    // 短信签名
    private static final String SIGN_NAME = "五子连珠";
    /**
     * 发送短信验证码方法
     * @param phone 手机号码
     * @param verify 验证码
     * @return true: 成功 false: 失败
     */
    public static boolean send(String phone, String verify){
        try {
            /** 可自助调整超时时间 */
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            /** 初始化acsClient,暂不支持region化 */
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                    ACCESS_KEY_ID,ACCESS_KEY_SECRET);
            /** cn-hangzhou: 中国.杭州 */
            DefaultProfile.addEndpoint("cn-hangzhou","cn-hangzhou",
                    PRODUCT, DOMAIN);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            /** 组装请求对象*/
            SendSmsRequest request = new SendSmsRequest();
            // 必填: 待发送手机号
            request.setPhoneNumbers(phone);
            // 必填: 短信签名-可在短信控制台中找到
            request.setSignName(SIGN_NAME);
            // 必填: 短信模板-可在短信控制台中找到
            request.setTemplateCode(TEMPLATE_CODE);
            /**
             * 可选: 模板中的变量替换JSON串,
             * 如模板内容为"亲爱的${name},您的验证码为${code}"
             */
            request.setTemplateParam("{\"number\":\"" + verify + "\"}");
            // hint 此处可能会抛出异常,注意catch
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            /** 判断短信是否发送成功 */
            return sendSmsResponse.getCode() != null &&
                    sendSmsResponse.getCode().equals("OK");
        }catch (Exception ex){
            throw new RuntimeException(ex);
        }
    }


}
package com.koohe.util;

import java.util.UUID;

public class Random {

    public static String generateCaptcha() {
        /** 生成6位随机数 */
        String captcha = UUID.randomUUID().toString()
                .replaceAll("-", "")
                .replaceAll("[a-z|A-Z]","")
                .substring(0, 6);
        return captcha;
    }

}
package com.koohe.service;

public interface SendMessageService {
    public Boolean sendMessage(String phone);
    public Boolean saveCaptcha(String captcha,String phone);
    public Boolean checkCaptcha(String captcha,String phone);
}

package com.koohe.service.impl;

import com.koohe.service.SendMessageService;
import com.koohe.util.Random;
import com.koohe.util.SmsSendUtil;
import io.lettuce.core.dynamic.domain.Timeout;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class SendMessageServiceImpl implements SendMessageService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Boolean sendMessage(String phone) {
        try {
            boolean data = SmsSendUtil.send(phone, Random.generateCaptcha());
            return data;
        } catch (Exception ex){
            throw new RuntimeException(ex);
        }

    }

    @Override
    public Boolean saveCaptcha(String captcha, String phone) {
        try {
        	//将验证码存储在redis中,并且设置过期时间,90s
            redisTemplate.boundValueOps(phone).set(captcha, 90, TimeUnit.SECONDS);
            return true;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public Boolean checkCaptcha(String captcha,String phone) {
        try {
            if (captcha.equals(redisTemplate.boundValueOps(phone).get())) {
                return true;
            } else {
                return false;
            }

        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}

package com.koohe.Controller;

import com.koohe.service.SendMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.annotation.Documented;

@RestController
public class SendMessageController {

    @Autowired
    private SendMessageService sendMessageService;


    @GetMapping("/sendCaptcha")
    public Boolean sendCaptcha(String phone) {
        try {
            Boolean data = sendMessageService.sendMessage(phone);
            return data;

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    @GetMapping("/saveCaptcha")
    public Boolean saveCaptcha(String captcha,String phone) {
        try {
            Boolean data = sendMessageService.saveCaptcha(captcha,phone);
            return data;

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    @GetMapping("/checkCaptcha")
    public Boolean checkCaptcha(String captcha,String phone) {
        try {
            Boolean data = sendMessageService.checkCaptcha(captcha,phone);
            return data;

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }
}

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值