80 distributed e-commerce project - SMS micro service

Keywords: Mobile Spring Java JSON

Now we need to build a general SMS sending service (independent of the separate project of pinyougou). The message (MAP type) received by activeMQ includes mobile number, template code, sign name and param.

code implementation

(1) create project pyg SMS (JAR project), and introduce dependency into POM file

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-activemq</artifactId>
		</dependency>
		<!-- Thermal deployment -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
		</dependency>
		<dependency>
			<groupId>com.aliyun</groupId>
			<artifactId>aliyun-java-sdk-core</artifactId>
			<version>3.2.8</version>
		</dependency>
		<dependency>
			<groupId>com.aliyun</groupId>
			<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
			<version>1.0.0-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>com.pinyougou</groupId>
			<artifactId>pyg-common</artifactId>
			<version>0.0.1-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-pool</artifactId>
			<version>5.13.3</version>
		</dependency>

(2) create a guide class

package com.pyg;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SmsApplication {
	
	public static void main(String[] args) {
		//Entrance
		SpringApplication.run(SmsApplication.class, args);
	}

}

(3) create the configuration file application.properties

server.port=90
#activeMQ url
spring.activemq.broker-url=tcp://192.168.25.128:61616
spring.activemq.pool.enabled=true
spring.activemq.packages.trust-all=true
spring.activemq.pool.max-connections=3000
#template code
template_code=Your template code
#
accessKeyId=Your keyid
accessKeySecret=Your secret key

(3) create SMS tool class

package com.pyg.utils;

public class SmsUtils {
	
	 //Product Name: cloud communication short message API product, developers do not need to replace it
    static final String product = "Dysmsapi";
    //Product domain name, developers do not need to replace
    static final String domain = "dysmsapi.aliyuncs.com";

    // TODO here needs to be replaced by the developer's own AK (found on Alibaba cloud access console)
   // static final String accessKeyId = "LTAIdSQD6Aw6mgLV";
   //final String accessKeySecret = "KFCVQ32sJmf3Yov8qRETNjX6jEfARR";
    public static SendSmsResponse sendSms(String mobile,String signName,String templateCode,String code,String accessKeyId,String accessKeySecret) throws ClientException {

        //Self adjustable timeout
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //Initialization of acsClient, region is not supported temporarily
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //Assembly request object - for details, please refer to the console - Documentation section
        SendSmsRequest request = new SendSmsRequest();
        //Required: mobile number to be sent
        request.setPhoneNumbers(mobile);
        //Required: SMS signature - can be found in SMS console
        request.setSignName(signName);
        //Required: SMS template - can be found in SMS console
        request.setTemplateCode(templateCode);
        //Optional: the variables in the template replace the JSON string. For example, when the template content is "Dear ${name}, and your verification code is ${code}", the value here is
        request.setTemplateParam(code);

        //Optional - uplink SMS extension code (please ignore this field for users without special requirements)
        //request.setSmsUpExtendCode("90997");

        //Optional: outId is the extension field provided to the business party, which will be brought back to the caller in the SMS receipt message.
        request.setOutId("yourOutId");

        //hint an exception may be thrown here. Pay attention to catch.
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        return sendSmsResponse;
    }


    public static QuerySendDetailsResponse querySendDetails(String mobile,String signName,String templateCode,String code,String accessKeyId,String accessKeySecret,String bizId) throws ClientException {

        //Self adjustable timeout
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //Initialization of acsClient, region is not supported temporarily
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //Assemble request object
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //Required - number
        request.setPhoneNumber(mobile);
        //Optional - serial number
        request.setBizId(bizId);
        //Required - send date supports query within 30 days, format yyyyMMdd
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        request.setSendDate(ft.format(new Date()));
        //Required - page size
        request.setPageSize(10L);
        //Required - the current page number is counted from 1
        request.setCurrentPage(1L);

        //hint an exception may be thrown here. Pay attention to catch.
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

        return querySendDetailsResponse;
    }

}

(4) message monitoring class

@Component
public class SmsListener {
@Autowired
private SmsUtil smsUtil;

@JmsListener(destination="sms")
public void sendSms(Map<String,String> map){
	try {
		SendSmsResponse response = smsUtil.sendSms(
		map.get("mobile"), 
		map.get("template_code"),
		map.get("sign_name"),
		map.get("param") );
		System.out.println("Code=" + response.getCode());
		System.out.println("Message=" + response.getMessage());
		System.out.println("RequestId=" + response.getRequestId());
		System.out.println("BizId=" + response.getBizId());
	} catch (ClientException e) {
		e.printStackTrace();
	} 
 }
}

Code testing

New SMSController

package com.pyg.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

@RestController
public class SmsController {

	// Inject jms template object
	@Autowired
	private JmsTemplate jmsTemplate;

	/**
	 * Requirement: Test SMS Gateway Service: send message queue: queue
	 */
	@RequestMapping("/sendSms")
	public void sendSms() {
		// Create map object
		Map<String, String> mapMessage = new HashMap<String, String>();
		// Put in message
		// Cell-phone number
		mapMessage.put("mobile", "18926243061");
		// autograph
		mapMessage.put("signName", "Dark horse");

		// Create map
		Map<String, String> map = new HashMap<String, String>();
		map.put("code", "787878");

		mapMessage.put("number", JSON.toJSONString(map));

		// Send message pyg SMS to SMS Gateway Service
		jmsTemplate.convertAndSend("smsQueue",JSON.toJSONString(mapMessage));
	}

}

Start pyg? SMS

Address field input: http://localhost:8088/sendsms.do

Observe console output

Then the SMS is sent successfully!

Posted by zhahaman2001 on Mon, 21 Oct 2019 14:37:56 -0700