SpringBoot整合阿里云短信服务

  • 准备工作
    • 开通短信服务(可参考博主的“手机短信验证码”)
    • 如果开通不成功,就只能借下别人已经开通好的短信,如果不想重复,可在其下创建一个新的模板管理
    • 这里只是介绍如何使用
  • 导入依赖
    <!--aliyun--> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>4.5.1</version> </dependency> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-dysmsapi</artifactId> <version>1.1.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency>
  • 编写配置文件
# 服务端口 server.port=8200 # 服务名称 spring.application.name=service-msg # 返回json的全局时间格式 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8 # redis配置 spring.redis.host=your_ip spring.redis.port=6379 spring.redis.database=0 spring.redis.timeout=1800000 spring.redis.lettuce.pool.max-active=20 # 最大阻塞等待时间(负数表示没限制) spring.redis.lettuce.pool.max-wait=-1 spring.redis.lettuce.pool.max-idle=5 spring.redis.lettuce.pool.min-idle=0 # aliyun 密钥及短信配置 aliyun.sms.accessKeyId=your_key aliyun.sms.secret=your_secret aliyun.sms.regionId=your_region_id aliyun.sms.signName=your_sign_name aliyun.sms.templateCode=your_template_code
  • 编写一个常量类,读取配置文件
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class ConstantPropertiesUtils implements InitializingBean { @Value("${aliyun.sms.regionId}") private String regionId; @Value("${aliyun.sms.accessKeyId}") private String accessKeyId; @Value("${aliyun.sms.secret}") private String secret; @Value("${aliyun.sms.signName}") private String signName; @Value("${aliyun.sms.templateCode}") private String templateCode; public static String REGION_ID; public static String ACCESS_KEY; public static String ACCESS_SECRET; public static String SIGN_NAME; public static String TEMPLATE_CODE; @Override public void afterPropertiesSet() throws Exception { REGION_ID = this.regionId; ACCESS_KEY = this.accessKeyId; ACCESS_SECRET = this.secret; SIGN_NAME = this.signName; TEMPLATE_CODE = this.templateCode; } }
  • 发送验证码到手机上,验证码生成工具类(内容较为固定,也可根据需求改)
    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; 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; @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(ConstantPropertiesUtils.REGION_ID, ConstantPropertiesUtils.ACCESS_KEY, ConstantPropertiesUtils.ACCESS_SECRET); IAcsClient client = new DefaultAcsClient(profile); SendSmsRequest request = new SendSmsRequest(); request.setPhoneNumbers(phone);//接收短信的手机号码 request.setSignName(ConstantPropertiesUtils.SING_NAME);//短信签名名称 request.setTemplateCode(ConstantPropertiesUtils.TEMPLATE_CODE);//短信模板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; } }

__EOF__

本文作者xsha_h
本文链接https://www.cnblogs.com/aitiknowledge/p/15958795.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   xsha_h  阅读(382)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示