欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

阿里短信服务的使用流程

发布时间:2025/7/14 39 豆豆
生活随笔 收集整理的这篇文章主要介绍了 阿里短信服务的使用流程 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

第一部分 前期准备

阿里短信服务-使用流程

1、注册阿里账号

2、获得accessKeyId和accessKeySecret

3、创建SmsSendUtil工具类

4、创建sendSms方法

5、将阿里发短信Demo核心代码复制为sendSms的方法体内

DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "<accessKeyId>", "<accessSecret>");IAcsClient client = new DefaultAcsClient(profile); ​CommonRequest request = new CommonRequest();request.setMethod(MethodType.POST);request.setDomain("dysmsapi.aliyuncs.com");request.setVersion("2017-05-25");request.setAction("SendSms");request.putQueryParameter("RegionId", "cn-hangzhou");request.putQueryParameter("PhoneNumbers", "177******75");request.putQueryParameter("SignName", "云商商城");request.putQueryParameter("TemplateCode", "SMS_171110064");request.putQueryParameter("TemplateParam", "{\"code\":\"6666\"}");try {CommonResponse response = client.getCommonResponse(request);System.out.println(response.getData());} catch (ServerException e) {e.printStackTrace();} catch (ClientException e) {e.printStackTrace();}

6、将相应的参数修改成变量

第二部分 阿里云短信服务的项目实现

一、阿里短信服务-消息中间件实现

Ⅰ、坐标依赖

1、单独使用

<dependencies><dependency><groupId>org.apache.activemq</groupId><artifactId>activemq-all</artifactId><version>5.13.4</version></dependency> </dependencies>

2、ActiveMQ和Spring整合JMS(此处使用的是整合)

<!-- spring 与 mq整合 start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.apache.xbean</groupId> <artifactId>xbean-spring</artifactId> <version>3.7</version> </dependency> <!-- spring 与 mq整合 end -->

Ⅱ、消息中间件发送方huawei_user_web执行消息的发送以及用户请求的接收,配置文件如下:spring-activemq-provider.xml 

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="targetConnectionFactory" class="org.apache.activemq.spring.ActiveMQConnectionFactory"><property name="brokerURL" value="tcp://192.168.25.134:61616"/></bean><bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory"><property name="targetConnectionFactory" ref="targetConnectionFactory"/></bean><bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"><property name="connectionFactory" ref="connectionFactory"/></bean><bean id="sendSms" class="org.apache.activemq.command.ActiveMQQueue"><constructor-arg value="sendSms"/></bean> </beans>

、调用消息发送的类UserController

package com.huawei.user.controller;import com.huawei.pojo.TbUser; import entity.Result; import org.apache.activemq.command.ActiveMQQueue; import org.apache.commons.lang3.RandomStringUtils; import org.apache.solr.common.util.Hash; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.MessageCreator; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; import java.util.HashMap; import java.util.Map;@RestController @RequestMapping("/userController") public class UserController {@AutowiredJmsTemplate jmsTemplate;@AutowiredActiveMQQueue sendSms;@RequestMapping("/add")public Result add(@RequestBody TbUser user){try{return new Result(true,"Success!");}catch (Exception e){return new Result(false,"Faild!");}}@RequestMapping("/createSmsCode")public Result createSmsCode(String phone){try{
       //apache 随机字符串工具类String random
= RandomStringUtils.randomNumeric(6);;HashMap map=new HashMap<String,String>();map.put("phone",phone);map.put("code",random);System.out.println(map);jmsTemplate.send(sendSms, new MessageCreator() {@Overridepublic Message createMessage(Session session) throws JMSException {return session.createObjectMessage(map);}});return new Result(true,"Success!");}catch (Exception e){return new Result(false,"Faild!");}} }

 

Ⅳ、创建huawei_sms模块war模块,创建监听类smsSendListener

@Component public class SmsSendListener implements MessageListener {@AutowiredSmsUtils smsUtils;@Overridepublic void onMessage(Message message) {ObjectMessage messageReslut = (ObjectMessage) message;try {Map objectMap = (Map) messageReslut.getObject();String phone = (String) objectMap.get("phone");String code = (String) objectMap.get("code"); // System.out.println(phone+"%%%%%%%%%%%%%%%%%%%"+code); smsUtils.sendSms(phone,code);} catch (JMSException e) {e.printStackTrace();}} }

 

Ⅴ、在huawei_sms中的springmvc中添加消息中间件的接收方的配置信息

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsdhttp://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><context:property-placeholder location="classpath:config/application.properties" /><context:component-scan base-package="com.huawei.sms.controller"/><mvc:annotation-driven><mvc:message-converters register-defaults="true"><bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"><property name="supportedMediaTypes" value="application/json"/><property name="features"><array><value>WriteMapNullValue</value><value>WriteDateUseDateFormat</value></array></property></bean></mvc:message-converters></mvc:annotation-driven><bean id="targetConnectionFactory" class="org.apache.activemq.spring.ActiveMQConnectionFactory"><property name="brokerURL" value="tcp://192.168.25.134:61616"/></bean><bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory"><property name="targetConnectionFactory" ref="targetConnectionFactory"/></bean><bean id="sendSms" class="org.apache.activemq.command.ActiveMQQueue"><constructor-arg value="sendSms"/></bean><bean class="org.springframework.jms.listener.DefaultMessageListenerContainer"><property name="connectionFactory" ref="connectionFactory"/><property name="destination" ref="sendSms"/><property name="messageListener" ref="smsSendListener"/></bean> </beans>

 

Ⅵ、发送短信息的controller工具类

package com.huawei.sms.controller;import com.aliyuncs.CommonRequest; import com.aliyuncs.CommonResponse; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; import com.aliyuncs.http.MethodType; import com.aliyuncs.profile.DefaultProfile; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;@RestController public class SmsUtils {@Value("${accessKeyId}")private String accessKeyId;@Value("${accessKeySecret}")private String accessKeySecret;@RequestMapping("/sendSms")public void sendSms(String phone,String code){DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);IAcsClient client = new DefaultAcsClient(profile);CommonRequest request = new CommonRequest();request.setMethod(MethodType.POST);request.setDomain("dysmsapi.aliyuncs.com");request.setVersion("2017-05-25");request.setAction("SendSms");request.putQueryParameter("RegionId", "cn-hangzhou");request.putQueryParameter("PhoneNumbers", phone);request.putQueryParameter("SignName", "云商商城");request.putQueryParameter("TemplateCode", "SMS_171110064");request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");try {CommonResponse response = client.getCommonResponse(request);System.out.println(response.getData());} catch (ServerException e) {e.printStackTrace();} catch (ClientException e) {e.printStackTrace();}} }

 实现验证码验证登录需要先把生成的验证码存入redis并设置生效时长

二、阿里短信服务-HttpClient实现( 不推荐)

Ⅰ、创建huawei_user_web,创建UserController,创建createSmsCode处理器(就是方法)

@RequestMapping("/createSmsCode")public Result createSmsCode(String phone){//验证手机号是否正确if(!PhoneFormatCheckUtils.isPhoneLegal(phone)){return new Result(false, "手机号不正确!!");}try {userService.createSmsCode(phone);return new Result(true, "发送成功");} catch (Exception e) {e.printStackTrace();return new Result(false, "发送失败");}}

使用的格式验证工具类【工具类使用了正则表达式,其实就是Matcher匹配器和Pattern模板的相互使用,将正则字符串编译进模板返回模板对象,再将待检测字符串通过模板的匹配比较器方法进行匹配后返回比较器对象,通过比较器对象的匹配方法返回布尔值】

import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException;public class PhoneFormatCheckUtils {/** * 大陆号码或香港号码均可 */ public static boolean isPhoneLegal(String str)throws PatternSyntaxException { return isChinaPhoneLegal(str) || isHKPhoneLegal(str); } /** * 大陆手机号码11位数,匹配格式:前三位固定格式+后8位任意数 * 此方法中前三位格式有: * 13+任意数 * 15+除4的任意数 * 18+除1和4的任意数 * 17+除9的任意数 * 147 */ public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException { String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$"; Pattern p = Pattern.compile(regExp); Matcher m = p.matcher(str); return m.matches(); } /** * 香港手机号码8位数,5|6|8|9开头+7位任意数 */ public static boolean isHKPhoneLegal(String str)throws PatternSyntaxException { String regExp = "^(5|6|8|9)\\d{7}$"; Pattern p = Pattern.compile(regExp); Matcher m = p.matcher(str); return m.matches(); } }

 Ⅱ、创建huawei_user_service的war工程,通过dubbo+zookeeper进行远程调用使用它的createSmsCode方法

【这里不适用dubbo,而是直接将Service建立在huawei_user_web的service(建立一个文件夹)路径下】

@Overridepublic void createSmsCode(String phone) {//随机6位数准备作为验证码String code = RandomStringUtils.randomNumeric(6);System.out.println("code==="+code);//httpClient通过http进行服务器间数据交互try {HttpClientUtil util = new HttpClientUtil("http://localhost:9002/sendSms.do?phone=" + phone + "&code=" + code);util.get();String content = util.getContent();System.out.println("content"+content);} catch (Exception e) {e.printStackTrace();}}

 

转载于:https://www.cnblogs.com/kitor/p/11233619.html

总结

以上是生活随笔为你收集整理的阿里短信服务的使用流程的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。