用阿里云短信服务--通过Web接口发送短信

本博客在上一篇博客:用阿里云短信服务--发送短信demo 的基础上进行!

 

实现功能:

1.通过Web接口请求调用发送短信方法发送短信验证码;

2.验证码保存在Redis中,并且设置有效时间为5分钟。

 

代码实现:

代码目录结构:

修改pom.xml,添加redis依赖

        <!--缓存数据-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.2.2.RELEASE</version>
        </dependency>

修改application.properties,添加redis配置

spring.redis.host=127.0.0.1
spring.redis.port=6379

SendSms.java

package com.example.demo.service;

import java.util.Map;

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

SendSmsImpl.java 

package com.example.demo.service.impl;

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.demo.service.SendSms;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class SendSmsImpl implements SendSms {

    public boolean send(String phoneNum, String templateCode, Map<String, Object> code) {
        //连接阿里云
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "<accessKeyId>", "<accessSecret>");//accessKeyId和accessSecret要替换成第一步申请到的值
        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", "老梁说java");//短信签名
        request.putQueryParameter("TemplateCode", templateCode);//短信模板号
        //构建一个短信验证码
//        HashMap<String, Object> map = new HashMap<String, Object>();
//        map.put("code",112233);
        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;
    }
}

注意:accessKeyId和accessSecret要替换成申请到的值 ;短信签名也要替换成自己的签名

SmsApiController.java

package com.example.demo.controller;

import com.aliyuncs.utils.StringUtils;
import com.example.demo.service.SendSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin //跨域
public class SmsApiController {
    @Autowired
    private SendSms sendSms;

    //注入Redis
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/send/{phone}")
    public String code(@PathVariable("phone") String phone){
        // 调用发送方法(模拟真实业务redis)
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return phone + ":" + code + "已存在,还没有过期";
        }
        // 生成随机验证码并存储到redis中
        code = UUID.randomUUID().toString().substring(0, 4);
        HashMap<String, Object> param = new HashMap<String, Object>();
        param.put("code", code);

        boolean isSend = sendSms.send(phone, "SMS_189762676", param);//第二个参数为短信模板号,注意替换

        if(isSend){//如果短信发送成功,将手机号和验证码发送到redis缓存起来,过期时间为5分钟
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return phone + ":" + code + " 发送成功";
        }
        return phone + ":" + code + " 发送失败";
    }
}

说明:发送短信到的号码是通过请求URL传来的

注意:sendSms.send(phone, "SMS_189762676", param);//第二个参数为短信模板号,注意替换

 

启动redis服务(需要先安装好redis)

进入cmd,输入如下命令,启动redis服务

redis-server

启动项目

浏览器发送请求,请求地址如下:

http://localhost:8080/send/手机号

注意:手机号注意替换为真实的手机号 

运行效果如下:验证码为1a06

手机收到的短信效果如下:

可以看到手机收到的验证码和浏览器的输出一致,都为1a06,

可以验证redis 有效期为5分钟

打开cmd命令行,输入进入redis客户端命令

redis-cli

通过get '手机号'来获取,是否有值

get '手机号'

正常情况是5分钟之内有能看到验证码的值,五分钟之后验证码过期后就看不到了。

 

 

参考链接:https://www.bilibili.com/video/BV1c64y1M7qN

 

完成! enjoy it!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值