使用activeMq发送短信(短信接口是山东鼎信)

*爱你&永不变心* 提交于 2019-12-10 09:48:58

一、引入依赖

        <!--activemq依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.jms</groupId>
            <artifactId>javax.jms-api</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!-- 阿里短信发送 -->

        <dependency>

            <groupId>org.apache.httpcomponents</groupId>

            <artifactId>httpclient</artifactId>

        </dependency>

        <dependency>

            <groupId>org.apache.httpcomponents</groupId>

            <artifactId>httpcore</artifactId>

        </dependency>

        <dependency>

            <groupId>commons-lang</groupId>

            <artifactId>commons-lang</artifactId>

            <version>2.6</version>

        </dependency>

        <dependency>

            <groupId>org.eclipse.jetty</groupId>

            <artifactId>jetty-util</artifactId>

        </dependency>

         <!-- redis依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- SpringBoot 相关 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.7.RELEASE</version>
        </dependency>

二、配置application.yml文件

# tomcat默认的端口8080
# http协议访问服务器默认的端口是80
server:
  port: 8080
spring:
  activemq:
    in-memory: true   # 放在缓存里面
    broker-url: tcp://127.0.0.1:61616  #需要启动mq服务

三、配置启动类

package com.tgz.ssm;

import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import javax.jms.Queue;

/**
 * Created by a8411 on 2019/11/22.
 */
@SpringBootApplication
public class HospitalApplication {
    public static void main(String[] args) {
        SpringApplication.run(HospitalApplication.class,args);
    }

    /**
     * 创建消息队列
     * @return
     */
    @Bean
    public Queue queue(){
        return new  ActiveMQQueue("smsCode");
    }

}

四、生成验证码以及发送验证码到mq队列中

package com.tgz.ssm.controller;

import com.alibaba.dubbo.config.annotation.Reference;

import com.tgz.ssm.entity.Patient;
import com.tgz.ssm.pojo.Result;
import com.tgz.ssm.pojo.StatusCode;
import com.tgz.ssm.service.PatientService;
import com.tgz.ssm.utils.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.jms.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Created by a8411 on 2019/11/22.
 */
@RestController
@RequestMapping("/patient")
public class PatientController {

    @Autowired
    private RedisTemplate redisTemplate;//redis用于用户接受短信判断
    
    @Autowired
        private Queue queue;	//引入队列名称

    @Autowired
    private JmsTemplate jms;	//jms发送消息
    /**
     * 获取验证码
     * @param patientPhone
     * @return
     */
    @RequestMapping("/getYzm")
    public StringgetYzm(String patientPhone){
         String code = "";
        for (int i=0;i<6;i++){
            code+=new Random().nextInt(10);
        }
        final String  codes  = code;
        //将短信存入mq
        jms.send(queue, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
            	//创建MapMessage将信息以key,value的形式存储 并发送到mq中
                MapMessage mapMessage = session.createMapMessage();
                mapMessage.setObject("code",codes);
                mapMessage.setObject("phone",patientPhone);
                return mapMessage;
            }
        });
        return "验证码已发送至您的手机";
    }


    /**
     * 通过监听获取 验证码以及手机号的队列
     */
    String mqCode = ""; //局部变量 供其他方法使用
    String mpPhone = "";
    //通过注解监听到队列 这里用的点对点 所以可以实时监听消息
    @JmsListener(destination = "smsCode")
    public void getMessage(Message message){
        //传的是键值对 取得时候也是通过 MapMessage 来取
        MapMessage  mapMessage1  = (MapMessage)message;
        try {
        	//获取队列中的消息
            mqCode = mapMessage1.getString("code");
            mpPhone = mapMessage1.getString("phone");
            //将数据存入redis中用于登录的时候进行判断
            redisTemplate.opsForValue().set(mpPhone,mqCode);
            //设置过期时间
            redisTemplate.expire(mpPhone,60, TimeUnit.SECONDS);
            //给患者发送短信到手机
            String host = "http://dingxin.market.alicloudapi.com";
            String path = "/dx/sendSms";
            String method = "POST";
            String appcode = "这里是你购买短信的appcode";
            Map<String, String> headers = new HashMap<String, String>();
            //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
            headers.put("Authorization", "APPCODE " + appcode);
            Map<String, String> query = new HashMap<String, String>();
            query.put("mobile", mpPhone);
            query.put("param", "code:"+mqCode);
            query.put("tpl_id", "TP1711063");
            Map<String, String> bodys = new HashMap<String, String>();
            try {
                /**
                 * 重要提示如下:
                 * HttpUtils请从
                 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
                 * 下载
                 *
                 * 相应的依赖请参照
                 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
                 */
                HttpResponse response = HttpUtils.doPost(host, path, method, headers, query, bodys);
                //获取response的body返回结果为00000则成功 其他的返回结果可参照短信api
                System.out.println(EntityUtils.toString(response.getEntity()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

五、前台代码获取短信开启倒计时

<!DOCTYPE html>
<html>
<head>
		<meta charset="utf-8">
		<title>TITLE</title>
</head>
	<body ng-app="regApp" ng-controller="regCtrl">
	
						<form>
								<input type="text"  placeholder="请您输入手机号" ng-model="phone" />						
								<input ng-model="code" type="text" placeholder="验证码">
								<button style="width: 300px;height: 40px"  ng-click="onClick()" ng-disabled="timer"><span ng-if="showTimer">{{timerCount}}</span>{{text}}</button>
								<input style="width: 300px;height: 40px" type="button"  ng-click="Reg()" value="点击注册">					
						</form>

	<script>
		var app = angular.module("regApp",[]);
		app.controller("regCtrl",function ($scope,$http,$interval,$timeout) {
            /**
             * 短信验证信息
             * @type {number}
             */
              		$scope.timer = false;
                    $scope.timeout = 60000;
                    $scope.timerCount = $scope.timeout / 1000;
                    $scope.text = "获取验证码";
                    $scope.onClick = function(){

                        //验证码发送的触发代码
                        $http.get("/doYzm?phone="+$scope.phone).then(function (response) {
                            if(response.data == "1"){
                                $scope.showTimer = true;
                                $scope.timer = true;
                                $scope.text = "秒后重新获取";
                                var counter = $interval(function(){
                                    $scope.timerCount = $scope.timerCount - 1;
                                }, 1000);
                                $timeout(function(){
                                    $scope.text = "获取验证码";
                                    $scope.timer = false;
                                    $interval.cancel(counter);
                                    $scope.showTimer = false;
                                    $scope.timerCount = $scope.timeout / 1000;
                                }, $scope.timeout);
                            }else{
                                alert("请输入手机号")
							}
                        })
                    };

            }
        })

	</script>
	</body>
</html>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!