Springboot实现阿里云短信验证服务+Redis缓存

Springboot实现阿里云短信验证+Redis缓存

本篇文章讲述在创建Springboot项目的基础之上,我们可以使用Redis实现缓存来完成阿里云的短信服务,在这里大家需要注意的是,我使用的jdk版本是21,但是在使用java的TimeUnit工具时,java无法识别,在网上看了好多人有同样的疑惑,我们也就不过多纠结这个问题,在对应的代码地方我会有另外的解决方案,或者换一个jdk版本就可以正常使用了。

在使用阿里云短信验证服务之前,我们需要有一个阿里云的账户然后在完成以下步骤:

开通阿里云短信验证

官网主页:https://www.aliyun.com/?spm=5176.25163407.console-base_top-nav.dlogo.7316bb6eKb8MCL

温馨提示:每次出现的key最好保存一下后面写代码的时候要用,并且只会在创建成后出现,过后就看不到了


当我们申请完凭证以后,我们添加用户组,在用户里面在添加用户

创建完用户组以后,我们需要给这个用户组添加短信权限:


接下来我们创建用户并把他分配到对应的用户组

开通阿里云短信服务

官网直达:https://dysms.console.aliyun.com/quickstart

我们做好上面的准备工作后,我们接着开通阿里云短信服务

当我们来到短信服务之后,我们需要按照下面的这几项步骤完成即可开通短信服务:

新增资质
申请签名


添加短信模板

待签名审核通过后,我们就可以选择我们需要的短信模板了,


另外场景说明写得体点,不然不给通过。

然后可以点击发起调用可以测试下的短信服务给开通了,对了记得充钱,没钱它用不了,下面是充钱的步骤,已有余额请跳过这一段:

bash 复制代码
https://www.aliyun.com/?spm=api-workbench.api_explorer.0.0.2e0d30c3JHigWq
创建Springboot项目测试

我们的短信验证到这里就准备完成了,下面直接上代码:

我们这里是创建了一个Springboot项目(不会的请移步到我的主页),做了一个微服务:

在pom.xml导入依赖:

xml 复制代码
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.0.3</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.49</version>
        </dependency>

		  <!--redis依赖 -->
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>3.2.4</version>
        </dependency>

SendSmsController:

java 复制代码
package com.example.redistest1.controller;

import com.aliyuncs.utils.StringUtils;
import com.example.redistest1.service.SendSms;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;


@CrossOrigin
@RestController

public class SendSmsController {


        @Autowired
        private SendSms sendSms;

        @Autowired
        private RedisTemplate<String,String> redisTemplate;


        @GetMapping("/getCode/{phone}")
        public String code(@PathVariable("phone") String phone){
    //      掉用发送方法
            String code  = redisTemplate.opsForValue().get(phone);
            if(!StringUtils.isEmpty(code)){

//                return "清除";
                return phone + ":" + code + "已存在,还没有过期";
            }

    //        生成验证码并存储到redis
            int min = 100000;
            int max = 999999;
            code = String.valueOf((int) (Math.random()* (max - min + 1)) + min);
            HashMap<String,Object> param = new HashMap<>();
            param.put("code",code);

    //        调用服务进行发送
             boolean isSend =  sendSms.send(phone,"你的短信模板",param);
            if (isSend){
 //           		如果使用JDK21运行的话,可能会是识别不出来,我们可以换成下面注释的两行代码也可以正常设置过期时间
  //                 设置过期时间为1分钟
                redisTemplate.opsForValue().set(phone, code,1, TimeUnit.MINUTES);
 //                 设置过期时间为30秒
//                redisTemplate.opsForValue().set(phone, code);
//                boolean isExpireSet = redisTemplate.expire(phone, Duration.ofSeconds(30));
                return phone + ":" + code + "发送成功";
            }else{
                return "发送失败";
            }
        }


}

大家需要在下图的标识中把短信模板的码换成自己的:

SendSmsImpl:

java 复制代码
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.example.redistest1.service.SendSms;
import org.springframework.stereotype.Service;

import java.util.Map;


@Service
public class SendSmsImpl implements SendSms {

    @Override
    public boolean send(String phoneNum, String templateCode, Map<String, Object> code) {

        // 连接阿里云
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "你的ID", "你的key");
        IAcsClient client = new DefaultAcsClient(profile);

//        构建请求
        CommonRequest request = new CommonRequest();

        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");


//        自定义参数
        request.putQueryParameter("PhoneNumbers",phoneNum);
        request.putQueryParameter("SignName","你的签名");
        request.putQueryParameter("TemplateCode",templateCode);
//        构建短信验证码
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(code));

        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}

SendSms.Interface:

java 复制代码
import java.util.Map;


public interface SendSms {
    public boolean send(String phoneNum, String templateCode, Map<String,Object> code);

}

另外在构建完Springboot之后,不要忘记安装和启动Redis服务:

Redis下载地址:https://redis.io/

今天的分享就到这里啦,感谢大家的阅览,小江会一直与大家一起努力,文章中如有不足之处,你的支持是我前进的最大动力,请多多指教,感谢支持,持续更新中 ......

相关推荐
seventeennnnn2 小时前
谢飞机的Java高级开发面试:从Spring Boot到分布式架构的蜕变之旅
spring boot·微服务架构·java面试·分布式系统·电商支付
超级小忍3 小时前
服务端向客户端主动推送数据的几种方法(Spring Boot 环境)
java·spring boot·后端
时间会给答案scidag3 小时前
报错 400 和405解决方案
vue.js·spring boot
Wyc724094 小时前
SpringBoot
java·spring boot·spring
傲祥Ax4 小时前
Redis总结
数据库·redis·redis重点总结
ladymorgana5 小时前
【Spring Boot】HikariCP 连接池 YAML 配置详解
spring boot·后端·mysql·连接池·hikaricp
夜斗小神社7 小时前
【黑马点评】(二)缓存
缓存
GJCTYU7 小时前
spring中@Transactional注解和事务的实战理解附代码
数据库·spring boot·后端·spring·oracle·mybatis
风象南8 小时前
SpringBoot敏感配置项加密与解密实战
java·spring boot·后端
写不出来就跑路9 小时前
暑期实习感悟与经验分享:从校园到职场的成长之路
java·开发语言·经验分享·spring boot