SpringBoot整合阿里云短信服务

创建SpringBoot工程

引入阿里云依赖

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.28</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
             <version>1.2.28</version>
        </dependency>

验证码随机生成工具类

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

阿里云模板截图

在这里插入图片描述待会要用到里面的签名,模版Code

Controller层

注意下面的Map存数据的key值要与模板内容的${code}一致,value是要发送的验证码


/**
 * @author MIS
 * @version 1.0
 * @description: TODO
 * @date 2022/8/12 15:42
 */
@Api(description = "短信发送")
@RestController
@RequestMapping("/edumsm/sms")
@CrossOrigin
public class SmsApiController {
    @Autowired
    SmsService smsService;
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @ApiOperation(value = "短信发送")
    @GetMapping("sendSmsPhone/{phone}")
    public R sendSmsPhone(@PathVariable String phone) {
        //1.拿到手机号到redis查询
        String rPhone = redisTemplate.opsForValue().get(phone);
        //2.验证码是否存在,直接返回ok
        if(rPhone !=null){
            return R.ok();
        }
        //3.不存在生成验证码
        String code = RandomUtil.getSixBitRandom();
        //4.调用短信接口服务发送验证码
        Map<String,String> parm=new HashMap<>();
        parm.put("code",code);
        boolean isSend=smsService.sendSmsPhone(phone,code,parm);
        //5.发送验证码成功,存入redis中,时效5分钟
if(isSend){
    redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
    return R.ok();
}else {
    return R.error();
}

    }

}

service层

/**
 * @author MIS
 * @version 1.0
 * @description: TODO
 * @date 2022/8/12 15:43
 */
@Service
public class SmsServiceImp implements SmsService {
    @Override
    public boolean sendSmsPhone(String phone, String code, Map<String, String> parm) {

        //发送短信
        if (StringUtils.isEmpty(phone)) return false;

        DefaultProfile profile =
                DefaultProfile.getProfile("default", "写自自己的AccessKey ID", "写自己的AccessKey Secret");
        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", "写自己的");//模版Code
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(parm));

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


}

启动服务,要记得买几条短信,要不然会发送失败

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值