• 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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    验证码随机生成工具类

    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;
    	}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51

    阿里云模板截图

    在这里插入图片描述待会要用到里面的签名,模版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();
    }
    
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

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

  • 相关阅读:
    常用工具概览
    在STM32F103C8T6上使用RT_Thread Nano移植控制台和Finsh
    最流行的 API 类型指南:REST、SOAP、GraphQL 和 gRPC
    辐射骚扰整改思路及方法:对共模电流的影响?|深圳比创达电子EMC
    ALV细节再梳理2022.8.5
    使用git将本地项目推送到远程仓库github
    竞赛选题 深度学习的水果识别 opencv python
    Vue3 - reactive 复杂类型(通俗易懂,详细教程)
    MySQL之误删数据如何处理
    Node.js躬行记(18)——半吊子的可视化搭建系统
  • 原文地址:https://blog.csdn.net/daai5201314/article/details/126319441