SpringBoot基于阿里云短信发送,yml配置

SpringBoot基于阿里云短信发送,yml配置

本篇文章是用SpringBoot基于阿里云短信服务,配置文件为yml配置
yml的配置
alisms:
    accessKeyId:  #ak
    accessSecret:   #sk
    enable: true
    templateCode:  #短信模板
    signName:  # 签名

由于我这边的需求是将发送成功的手机号和短信发送的手机号都要保存到数据库,所以我这边是封装了一个实体类

@ApiModel(description = "Counts",value = "Counts")
@Table(name="counts")
public class Counts implements Serializable {
    /**
     * 编号
     */
    @ApiModelProperty(value = "",required = false)
    @Id
    @Column(name = "id")
    private Integer id;
    /**
     * 日期
     */
    @ApiModelProperty(value = "",required = false)
    @Column(name = "times")
    private Date times;
    /**
     * 手机号
     */
    @ApiModelProperty(value = "",required = false)
    @Column(name = "number")
    private String number;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public Date getTimes() {
        return times;
    }
    public void setTimes(Date times) {
        this.times= times;
    }
    public String getNumber() {
        return number;
    }
    public void setNumber(String number) {
        this.number = number;
    }
}
Service层
   /**
     * 发送短信
     * @param para 将验证码封装成一个map
     * @param phone 需要发送的手机号
     * @return
     */
    Result send(Map<String, Object> para, String phone);
ServiceImpl 实现类
@Service
public class MsmServiceImpl implements MsmService {

    @Value("${alisms.accessKeyId}")
    private String accessKeyId;
    @Value("${alisms.accessSecret}")
    private String accessSecret;
    @Value("${alisms.signName}")
    private String signName;
    @Value("${alisms.templateCode}")
    private String templateCode;
    @Autowired
    private CountsMapper countsMapper;

    @Override
    public Result send(Map<String, Object> para, String phone) {
        //创建一个实体类
        Counts counts = new Counts();
        //判断手机号是否为空
        if (StringUtils.isEmpty(phone)) {
            return new Result(false, StatusCode.ERROR,"手机号码为空");
        }
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(para));
        //最终发送
        try {
            CommonResponse response = client.getCommonResponse(request);
            boolean success = response.getHttpResponse().isSuccess();
            //判断短信是否发送成功
            if (success){
                //将号码保存到counts
                counts.setNumber(phone);
                //获取当前时间,保存到counts
                Date date = new Date();
                counts.setPeriod(date);
                //添加到数据库
                countsMapper.addCounts(counts);
            }
            return new Result(true,StatusCode.OK,"验证码发送成功");
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(true,StatusCode.OK,"验证码发送失败");
        }

    }
}

这边提供一个生产随机数的工具类
public class ValidateCodeUtils {
    /**
     * 随机生成验证码
     * @param length 长度为4位或者6位
     * @return
     */
    public static Integer generateValidateCode(int length){
        Integer code =null;
        if(length == 4){
            code = new Random().nextInt(9999);//生成随机数,最大为9999
            if(code < 1000){
                code = code + 1000;//保证随机数为4位数字
            }
        }else if(length == 6){
            code = new Random().nextInt(999999);//生成随机数,最大为999999
            if(code < 100000){
                code = code + 100000;//保证随机数为6位数字
            }
        }else{
            throw new RuntimeException("只能生成4位或6位数字验证码");
        }
        return code;
    }

    /**
     * 随机生成指定长度字符串验证码
     * @param length 长度
     * @return
     */
    public static String generateValidateCode4String(int length){
        Random rdm = new Random();
        String hash1 = Integer.toHexString(rdm.nextInt());
        String capstr = hash1.substring(0, length);
        return capstr;
    }
}
Controller层
pub lic class SMSController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @ApiOperation(value = "发送短信", notes = "发送短信方法详情", tags = {"SMSController"})
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "phone", value = "手机号", required = true, dataType = "Integer")
    })
    @GetMapping("/send/{phone}")
    public Result sendMsg(@PathVariable String phone) {
        //从redis中获取验证码
        String code = redisTemplate.opsForValue().get(phone);
        //判断是否有验证码
        if (!StringUtils.isEmpty(code)){
            return new Result(true,StatusCode.OK,"验证码存在");
        }
        //生成随机数
        code = ValidateCodeUtils.generateValidateCode4String(4);
        Map<String, Object> para = new HashMap<>();
        para.put("code", code);
        Result send = msmService.send(para, phone);
        //如果返回的信息为StatusCode.OK
        if (send.getCode()==StatusCode.OK) {
            //将验证码存到redis中,并设置有效时间为5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return new Result(true, StatusCode.OK, "验证码发送成功", true);
        }else {

            return new Result(true, StatusCode.ERROR, "验证码发送失败");
        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值