SpringBoot整合阿里云开通短信服务详解

 更新时间:2022年03月23日 09:53:53   作者:fhadmin  
这篇文章主要介绍了如何利用SpringBoot整合阿里云实现短信服务的开通,文中的示例代码讲解详细,对我们学习有一定帮助,需要的可以参考一下

准备工作

开通短信服务

如果开通不成功,就只能借下别人已经开通好的短信,如果不想重复,可在其下创建一个新的模板管理

这里只是介绍如何使用

导入依赖

com.aliyun aliyun-java-sdk-core 4.5.1 com.aliyun aliyun-java-sdk-dysmsapi 1.1.0 com.alibaba fastjson 1.2.62

发送验证码到手机上,验证码生成工具类(内容较为固定,也可根据需求改)

package com.xsha.msmservice.utils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * 说明:短信配置
 * 作者:FH Admin
 * from:fhadmin.cn
 */
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;
	}
}

发送验证码,验证码是有有效时间的(时间可以自己设置)

这里可以创建常量类读取配置文件的阿里云密钥等信息

package com.xsha.msmservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xsha.msmservice.service.MsmService;
import com.xsha.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

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

/**
 * 说明:短信配置
 * 作者:FH Admin
 * from:fhadmin.cn
 */
@Service
public class MsmServiceImpl implements MsmService {

    // 注入redis缓存对象
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean sendMessage(String phone) {
        if(StringUtils.isEmpty(phone)) return false;
        // 先获取手机号对应的验证码(该验证码没过期)
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) {
            return true;
        }
        // 过期则生成随机验证码,并在发送之后向redis中存入手机号对应的验证码
        code = RandomUtil.getFourBitRandom();
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);

        // 设置短信配置
        DefaultProfile profile = DefaultProfile.getProfile("your region", "your accessId", "your accessSecret");

        IAcsClient client = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phone);//接收短信的手机号码
        request.setSignName("your signature name");//短信签名名称
        request.setTemplateCode("your template");//短信模板CODE
        request.setTemplateParam(JSONObject.toJSONString(map));//短信模板变量对应的实际值

        try {
            SendSmsResponse response = client.getAcsResponse(request);
            // 发送短信,尽量打印出来是否发送成功
            new Gson().toJson(response);
            // 将验证码放置在redis缓存中,并设置5分钟有效时间,最后一个参数是单位
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
        } catch (ServerException e) {
            e.printStackTrace();
            return false;
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}

到此这篇关于SpringBoot整合阿里云开通短信服务详解的文章就介绍到这了,更多相关SpringBoot阿里云短信内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java读取xml配置参数代码实例

    java读取xml配置参数代码实例

    这篇文章主要介绍了java读取xml配置参数代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • java 如何查看jar包加载顺序

    java 如何查看jar包加载顺序

    这篇文章主要介绍了java 如何查看jar包加载顺序,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-12-12
  • SpringBoot使用hutool-captcha实现验证码生成与验证

    SpringBoot使用hutool-captcha实现验证码生成与验证

    在springboot的登陆页面中为了防止机器大规模注册,机器暴力破解数据密码等危害,需要验证随机生成的验证码,本文主要介绍了SpringBoot使用hutool-captcha实现验证码生成与验证,感兴趣的可以了解一下
    2023-12-12
  • Java字符串相关类StringBuffer的用法详解

    Java字符串相关类StringBuffer的用法详解

    java.lang包下的StringBuffer类,代表着可变的字符序列,可以用来对字符串内容进行增删改操作。本文将通过示例详细说说它的用法,感兴趣的可以跟随小编一起学习一下
    2022-10-10
  • SpringSecurity进行认证与授权的示例代码

    SpringSecurity进行认证与授权的示例代码

    SpringSecurity是Spring家族中的一个安全管理框架,而认证和授权也是SpringSecurity作为安全框架的核心功能,本文主要介绍了SpringSecurity进行认证与授权的示例代码,感兴趣的可以了解一下
    2024-06-06
  • 基于Class.forName()用法及说明

    基于Class.forName()用法及说明

    这篇文章主要介绍了基于Class.forName()用法及说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • JavaWeb动态导出Excel可弹出下载

    JavaWeb动态导出Excel可弹出下载

    这篇文章主要介绍了JavaWeb动态导出Excel,对Excel可弹出进行下载操作,感兴趣的小伙伴们可以参考一下
    2016-03-03
  • java Collection 之List学习介绍

    java Collection 之List学习介绍

    本篇文章小编为大家介绍,java Collection 之List学习介绍。需要的朋友参考下
    2013-04-04
  • Java实现XML与JSON秒级转换示例详解

    Java实现XML与JSON秒级转换示例详解

    这篇文章主要为大家介绍了Java实现XML与JSON秒级转换示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-09-09
  • Java代码实现Map和Object互转及Map和Json互转

    Java代码实现Map和Object互转及Map和Json互转

    这篇文章主要介绍了Java代码实现map和Object互转及Map和json互转的相关资料,需要的朋友可以参考下
    2016-05-05

最新评论