使用阿里云的短信服务发送短信

喜欢ヅ旅行 2023-07-06 04:54 93阅读 0赞
  1. 首先你要有accessKeyIdaccessKeySecret,还不知道的同学就先去阿里云注册一个开发者账号,搞一下短信的签名管理和模版管理吧,我这里就不多说了,(还不会的同学就自己取百度吧!),这是我的项目结构:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMyNTY1MjY3_size_16_color_FFFFFF_t_70

SmsProperties.class:

  1. import lombok.Data;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. /**
  4. * @author hx <br>
  5. * @Title: <br>
  6. * @Package <br>
  7. * @Description: 短信发送配置类 <br>
  8. * @date 2020/2/1515:14
  9. */
  10. @Data
  11. @ConfigurationProperties(prefix = "ly.sms")
  12. public class SmsProperties {
  13. String accessKeyId;
  14. String accessKeySecret;
  15. String signName;
  16. String verifyCodeTemplate;
  17. }
  18. SmsListener.class
  19. import com.leyou.common.utils.JsonUtils;
  20. import com.leyou.sms.config.SmsProperties;
  21. import com.leyou.sms.utils.SmsUtils;
  22. import lombok.extern.slf4j.Slf4j;
  23. import org.apache.commons.lang3.StringUtils;
  24. import org.springframework.amqp.core.ExchangeTypes;
  25. import org.springframework.amqp.rabbit.annotation.Exchange;
  26. import org.springframework.amqp.rabbit.annotation.Queue;
  27. import org.springframework.amqp.rabbit.annotation.QueueBinding;
  28. import org.springframework.amqp.rabbit.annotation.RabbitListener;
  29. import org.springframework.beans.factory.annotation.Autowired;
  30. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  31. import org.springframework.stereotype.Component;
  32. import org.springframework.util.CollectionUtils;
  33. import java.util.Map;
  34. /**
  35. * @author hx <br>
  36. * @Title: <br>
  37. * @Package <br>
  38. * @Description: 监听是否发送短信<br>
  39. * @date 2020/2/1515:40
  40. */
  41. @Slf4j
  42. @Component
  43. @EnableConfigurationProperties(SmsProperties.class)
  44. public class SmsListener {
  45. @Autowired
  46. private SmsProperties prop;
  47. @Autowired
  48. private SmsUtils smsUtils;
  49. /**
  50. * 仅发送短信验证码
  51. * @param
  52. */
  53. @RabbitListener(bindings = @QueueBinding(
  54. value = @Queue(name = "sms.verify.code.queue",durable = "true"),
  55. exchange = @Exchange(name = "ly.sms.exchange",type = ExchangeTypes.TOPIC),
  56. key = {"sms.verify.code"}
  57. ))
  58. public void listenInsertAndUpdate(Map<String,String> msg){
  59. if(CollectionUtils.isEmpty(msg)){
  60. return;
  61. }
  62. String phone = msg.remove("phone");//删除并获取
  63. if(StringUtils.isBlank(phone)){
  64. return;
  65. }
  66. smsUtils.sendSms(phone,prop.getSignName(), prop.getVerifyCodeTemplate(), JsonUtils.serialize(msg));
  67. //发送短信日志
  68. log.error("[短信服务],发送短信验证码,手机号:{}",phone);
  69. }
  70. }
  71. SmsUtils.class
  72. package com.leyou.sms.utils;
  73. import com.aliyuncs.DefaultAcsClient;
  74. import com.aliyuncs.IAcsClient;
  75. import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
  76. import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
  77. import com.aliyuncs.exceptions.ClientException;
  78. import com.aliyuncs.http.MethodType;
  79. import com.aliyuncs.profile.DefaultProfile;
  80. import com.aliyuncs.profile.IClientProfile;
  81. import com.leyou.sms.config.SmsProperties;
  82. import lombok.extern.slf4j.Slf4j;
  83. import org.springframework.beans.factory.annotation.Autowired;
  84. import org.springframework.boot.context.properties.ConfigurationProperties;
  85. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  86. import org.springframework.data.redis.core.StringRedisTemplate;
  87. import org.springframework.stereotype.Component;
  88. /**
  89. * @author hx <br>
  90. * @Title: <br>
  91. * @Package <br>
  92. * @Description: 读取短信发送的配置文件<br>
  93. * @date 2020/2/1515:21
  94. */
  95. @Slf4j
  96. @Component
  97. @EnableConfigurationProperties(SmsProperties.class)
  98. public class SmsUtils {
  99. @Autowired
  100. private SmsProperties smsProperties;
  101. @Autowired
  102. private StringRedisTemplate redisTemplate;
  103. private static final String KEY_PREFIX = "sms:phone:";
  104. //短信发送的最小周期1分钟
  105. private static final long SMS_MIN_INTERVAL_MILLIS = 60000;
  106. //产品名称:云通信短信API产品,开发者无需替换
  107. static final String product = "Dysmsapi";
  108. //产品域名,开发者无需替换
  109. static final String domain = "dysmsapi.aliyuncs.com";
  110. /**
  111. * 给指定到用户发短信
  112. * @param phoneNumber 目标电话
  113. * @param signName 短信签名
  114. * @param templateCode 短信模板
  115. * @param templateParam 短信内容
  116. * @return
  117. * @throws ClientException
  118. */
  119. public SendSmsResponse sendSms(String phoneNumber,String signName,String templateCode,String templateParam) {
  120. String key = KEY_PREFIX + phoneNumber;
  121. //根据当前时间和上次发短信的时间对比,如果小于一分钟不进行发送,实现限流的效果
  122. //读取redis中的发短信的时间
  123. String lastTime = redisTemplate.opsForValue().get(key);
  124. if(System.currentTimeMillis() - Long.valueOf(lastTime) < SMS_MIN_INTERVAL_MILLIS){
  125. log.error("[短信服务] 发送短信频率过高,被阻止!phoneNumber:{}",phoneNumber);
  126. return null;
  127. }
  128. try {
  129. //可自助调整超时时间
  130. System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
  131. System.setProperty("sun.net.client.defaultReadTimeout", "10000");
  132. //初始化acsClient,暂不支持region化
  133. IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", smsProperties.getAccessKeyId(), smsProperties.getAccessKeySecret());
  134. DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
  135. IAcsClient acsClient = new DefaultAcsClient(profile);
  136. //组装请求对象-具体描述见控制台-文档部分内容
  137. SendSmsRequest request = new SendSmsRequest();
  138. request.setMethod(MethodType.POST);
  139. //必填:待发送手机号
  140. request.setPhoneNumbers(phoneNumber);
  141. //必填:短信签名-可在短信控制台中找到
  142. request.setSignName(signName);
  143. //必填:短信模板-可在短信控制台中找到
  144. request.setTemplateCode(templateCode);
  145. //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
  146. request.setTemplateParam(templateParam);
  147. //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
  148. //request.setSmsUpExtendCode("90997");
  149. //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
  150. // request.setOutId("123456");
  151. //hint 此处可能会抛出异常,注意catch
  152. SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
  153. if (!"OK".equals(sendSmsResponse.getCode())){
  154. log.info("[短信服务] 发送短信失败!phoneNumber:{},原因{}",phoneNumber,sendSmsResponse.getMessage());
  155. }
  156. //发送成功以后写入Redis,
  157. redisTemplate.opsForValue().set(key,String.valueOf(System.currentTimeMillis()));
  158. return sendSmsResponse;
  159. }catch (Exception e){
  160. log.error("[短信服务] 发送短信异常phoneNumber:{}",phoneNumber);
  161. return null;
  162. }
  163. }
  164. }
  165. LySmsApplication.class
  166. @SpringBootApplication
  167. public class LySmsApplication {
  168. public static void main(String[] args) {
  169. SpringApplication.run(LySmsApplication.class, args);
  170. }
  171. }

application.yml

  1. server:
  2. port: 8086
  3. spring:
  4. application:
  5. name: sms-service
  6. rabbitmq:
  7. host: 192.168.6.129
  8. username: leyou
  9. password: leyou
  10. virtual-host: /leyou
  11. redis:
  12. host: 192.168.6.129
  13. ly: #自定义短信
  14. sms:
  15. accessKeyId: xxxx # 你自己的accessKeyId
  16. accessKeySecret: xxxx # 你自己的AccessKeySecret
  17. signName: 商城 # 签名名称
  18. verifyCodeTemplate: xxx # 模板名称

pom.xml

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-amqp</artifactId>
  9. </dependency>
  10. <dependency>
  11. <groupId>com.aliyun</groupId>
  12. <artifactId>aliyun-java-sdk-core</artifactId>
  13. <version>3.3.1</version>
  14. </dependency>
  15. <dependency>
  16. <groupId>com.aliyun</groupId>
  17. <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
  18. <version>1.0.0</version>
  19. </dependency>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-configuration-processor</artifactId>
  23. <optional>true</optional>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.projectlombok</groupId>
  27. <artifactId>lombok</artifactId>
  28. <version>1.16.20</version>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.apache.commons</groupId>
  32. <artifactId>commons-lang3</artifactId>
  33. <version>3.9</version>
  34. </dependency>
  35. <dependency>
  36. <groupId>com.leiyou.common</groupId>
  37. <artifactId>ly-common</artifactId>
  38. <version>1.0-SNAPSHOT</version>
  39. </dependency>
  40. <dependency>
  41. <groupId>org.springframework.boot</groupId>
  42. <artifactId>spring-boot-starter-test</artifactId>
  43. <scope>test</scope>
  44. </dependency>
  45. <dependency>
  46. <groupId>org.springframework.boot</groupId>
  47. <artifactId>spring-boot-starter-data-redis</artifactId>
  48. </dependency>
  49. </dependencies>

Test.class

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. public class SmsListenerTest {
  4. @Autowired
  5. private AmqpTemplate amqpTemplate;
  6. @Test
  7. public void listenInsertAndUpdate() throws InterruptedException {
  8. HashMap<String, String> map = new HashMap<>();
  9. map.put("phone", "18623986825");
  10. map.put("code", "12345");
  11. //交换机,key
  12. amqpTemplate.convertAndSend("ly.sms.exchange", "sms.verify.code", map);
  13. Thread.sleep(10000L);
  14. }
  15. }

发表评论

表情:
评论列表 (有 0 条评论,93人围观)

还没有评论,来说两句吧...

相关阅读

    相关 阿里服务

    在开发过程中遇到过短信服务,推荐使用阿里云。个人申请阿里云短信服务确实有些困难,下面我先来简单说一下我的个人申请过程(仅供参考)。 1、申请签名流程 作为开发者,我们大