阿里短信服务的使用流程
生活随笔
收集整理的這篇文章主要介紹了
阿里短信服务的使用流程
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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();}Ⅰ、坐標(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 -->?
<?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>Ⅲ
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!");}} }
?
@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();}} }
?
Ⅴ、
<?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)
@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è)字符串通過模板的匹配比較器方法進(jìn)行匹配后返回比較器對(duì)象,通過比較器對(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開頭+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)建工程,通過dubbo+zookeeper進(jìn)行遠(yuǎn)程調(diào)用使用它的createSmsCode方法
【這里不適用dubbo,而是直接將Service建立在的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通過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)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue 项目中 点击回车键 自动登录
- 下一篇: c++ 动态规划(数塔)