阿里短信服务的使用流程
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(); }
Ⅰ、坐标依赖
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 -->
<?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/beans http://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 { @Autowired JmsTemplate jmsTemplate; @Autowired ActiveMQQueue 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() { @Override public 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 { @Autowired SmsUtils smsUtils; @Override public 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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd http://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并设置生效时长
@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(); } }
Ⅱ、创建createSmsCode方法
工程,通过dubbo+zookeeper进行远程调用使用它的【这里不适用dubbo,而是直接将Service建立在
的service(建立一个文件夹)路径下】@Override public 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(); } }