aliyun短信服务包含随机生成四位数字验证码工具类

.1.pom文件

<dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.6.0</version>
        </dependency>

        <!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

配置文件

spring:
 
   redis:
     host: localhost
     post: 6379
     database: 0
     timeout: 1800000

2.定义接口及实现类


public interface MsmService {
    //发送验证码
    boolean send(HashMap<String, Object> param, String phone);
}


import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.utils.StringUtils;
import lombok.Data;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Data
@Service
public class MsmServiceImpl implements MsmService {

    /**
     * 发送验证码
     * @param param     验证码
     * @param phone     手机号
     * @return
     */
    public boolean send(HashMap<String, Object> param, String phone) {

        if(StringUtils.isEmpty(phone)) return false;

        //default 地域节点,默认就好  后面是 阿里云的 id和秘钥(这里记得去阿里云复制自己的id和秘钥哦)
        DefaultProfile profile = DefaultProfile.getProfile("default", "LTAI5tE69LuEkxnLKEEGcTMy", "eR0A1fiHIu9z6mBaUaFjaivyTT2w2K");
        IAcsClient client = new DefaultAcsClient(profile);


        //这里不能修改
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        request.putQueryParameter("PhoneNumbers", phone);                    //手机号
        request.putQueryParameter("SignName", "阿里云短信测试");    //申请阿里云 签名名称(暂时用阿里云测试的,自己还不能注册签名)
        request.putQueryParameter("TemplateCode", "SMS_154950909"); //申请阿里云 模板code(用的也是阿里云测试的)
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

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


3.随机生成四位数字验证码工具类

package com.example.demo.util;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
//生成随机验证码
public class RandomUtil {

    private static final Random random = new Random();

    private static final DecimalFormat fourdf = new DecimalFormat("0000");

    private static final DecimalFormat sixdf = new DecimalFormat("000000");

    public static String getFourBitRandom() {
        return fourdf.format(random.nextInt(10000));
    }

    public static String getSixBitRandom() {
        return sixdf.format(random.nextInt(1000000));
    }

    /**
     * 给定数组,抽取n个数据
     * @param list
     * @param n
     * @return
     */
    public static ArrayList getRandom(List list, int n) {

        Random random = new Random();

        HashMap<Object, Object> hashMap = new HashMap<Object, Object>();

        // 生成随机数字并存入HashMap
        for (int i = 0; i < list.size(); i++) {

            int number = random.nextInt(100) + 1;

            hashMap.put(number, i);
        }

        // 从HashMap导入数组
        Object[] robjs = hashMap.values().toArray();

        ArrayList r = new ArrayList();

        // 遍历数组并打印数据
        for (int i = 0; i < n; i++) {
            r.add(list.get((int) robjs[i]));
            System.out.print(list.get((int) robjs[i]) + "\t");
        }
        System.out.print("\n");
        return r;
    }

}

3.controller类

@RestController
@RequestMapping("/api/msm")
public class MsmApiController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    //发送短信验证码

    @GetMapping(value = "/send/{phone}")
    public Boolean code(@PathVariable String phone) {
        if (StringUtils.isEmpty(phone)||StringUtils.isBlank(phone)){
            return false;
        }

        String fourBitRandom = RandomUtil.getFourBitRandom();
        String key="regist-"+phone;
        String value= redisTemplate.opsForValue().get("key");
        if(value!=null){
            return false;
        }
        HashMap<String,Object> code=new HashMap<>();
        code.put("code",fourBitRandom);
        if(msmService.send(code,phone)){
            redisTemplate.opsForValue().set(key,fourBitRandom,1, TimeUnit.MINUTES);
            return true;
        }
        return false;

    }


}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值