日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

阿里短信服务的使用流程

發(fā)布時(shí)間:2025/7/14 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 阿里短信服务的使用流程 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

第一部分 前期準(zhǔn)備

阿里短信服務(wù)-使用流程

1、注冊(cè)阿里賬號(hào)

2、獲得accessKeyId和accessKeySecret

3、創(chuàng)建SmsSendUtil工具類

4、創(chuàng)建sendSms方法

5、將阿里發(fā)短信Demo核心代碼復(fù)制為sendSms的方法體內(nèi)

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、將相應(yīng)的參數(shù)修改成變量

第二部分 阿里云短信服務(wù)的項(xiàng)目實(shí)現(xiàn)

一、阿里短信服務(wù)-消息中間件實(shí)現(xiàn)

Ⅰ、坐標(biāo)依賴

1、單獨(dú)使用

<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 -->

Ⅱ、消息中間件發(fā)送方huawei_user_web執(zhí)行消息的發(fā)送以及用戶請(qǐng)求的接收,配置文件如下: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>

、調(diào)用消息發(fā)送的類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 隨機(jī)字符串工具類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!");}} }

?

Ⅳ、創(chuàng)建huawei_sms模塊war模塊,創(chuàng)建監(jiān)聽(tīng)類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>

?

Ⅵ、發(fā)送短信息的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();}} }

?實(shí)現(xiàn)驗(yàn)證碼驗(yàn)證登錄需要先把生成的驗(yàn)證碼存入redis并設(shè)置生效時(shí)長(zhǎng)

二、阿里短信服務(wù)-HttpClient實(shí)現(xiàn)( 不推薦)

Ⅰ、創(chuàng)建huawei_user_web,創(chuàng)建UserController,創(chuàng)建createSmsCode處理器(就是方法)

@RequestMapping("/createSmsCode")public Result createSmsCode(String phone){//驗(yàn)證手機(jī)號(hào)是否正確if(!PhoneFormatCheckUtils.isPhoneLegal(phone)){return new Result(false, "手機(jī)號(hào)不正確!!");}try {userService.createSmsCode(phone);return new Result(true, "發(fā)送成功");} catch (Exception e) {e.printStackTrace();return new Result(false, "發(fā)送失敗");}}

使用的格式驗(yàn)證工具類【工具類使用了正則表達(dá)式,其實(shí)就是Matcher匹配器和Pattern模板的相互使用,將正則字符串編譯進(jìn)模板返回模板對(duì)象,再將待檢測(cè)字符串通過(guò)模板的匹配比較器方法進(jìn)行匹配后返回比較器對(duì)象,通過(guò)比較器對(duì)象的匹配方法返回布爾值】

import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException;public class PhoneFormatCheckUtils {/** * 大陸號(hào)碼或香港號(hào)碼均可 */ public static boolean isPhoneLegal(String str)throws PatternSyntaxException { return isChinaPhoneLegal(str) || isHKPhoneLegal(str); } /** * 大陸手機(jī)號(hào)碼11位數(shù),匹配格式:前三位固定格式+后8位任意數(shù) * 此方法中前三位格式有: * 13+任意數(shù) * 15+除4的任意數(shù) * 18+除1和4的任意數(shù) * 17+除9的任意數(shù) * 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(); } /** * 香港手機(jī)號(hào)碼8位數(shù),5|6|8|9開(kāi)頭+7位任意數(shù) */ 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(); } }

?Ⅱ、創(chuàng)建huawei_user_service的war工程,通過(guò)dubbo+zookeeper進(jìn)行遠(yuǎn)程調(diào)用使用它的createSmsCode方法

【這里不適用dubbo,而是直接將Service建立在huawei_user_web的service(建立一個(gè)文件夾)路徑下】

@Overridepublic void createSmsCode(String phone) {//隨機(jī)6位數(shù)準(zhǔn)備作為驗(yàn)證碼String code = RandomStringUtils.randomNumeric(6);System.out.println("code==="+code);//httpClient通過(guò)http進(jìn)行服務(wù)器間數(shù)據(jù)交互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();}}

?

轉(zhuǎn)載于:https://www.cnblogs.com/kitor/p/11233619.html

總結(jié)

以上是生活随笔為你收集整理的阿里短信服务的使用流程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。