把短信验证码储存在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

把短信验证码储存在Redis_第1张图片

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;
    }
}


看下这篇文章
https://blog.csdn.net/qq_43816654/article/details/121649028?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522169691900716800197011839%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=169691900716800197011839&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2alltop_click~default-1-121649028-null-null.142v95insert_down1&utm_term=redisTemplate.boundValueOps&spm=1018.2226.3001.4187

你可能感兴趣的:(redis,bootstrap,数据库)