How to call Ali SMS in springcloud project

Keywords: Java Spring SDK Apache

Catalog

premise

Build SMS micro service

1. Introduce pom dependency

2. Preparation of yml documents

3. Create a new guide class

4. Create a new read configuration class

5. Create a new tool class (integrated Alibaba cloud code)

6. Create a new message listening class

test

 

premise

 

Open Alibaba SMS service, see blog

https://blog.csdn.net/Delicious_Life/article/details/104428087

 

 

Build SMS micro service

 

1. Introduce pom dependency

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>3.3.1</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
    </dependencies>

 

2. Preparation of yml documents

 

3. Create a new guide class

package com.leyou;

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

@SpringBootApplication
public class LeyouSmsApplication {
    public static void main(String[] args) {
        SpringApplication.run(LeyouSmsApplication.class);
    }
}

 

4. Create a new read configuration class

package com.leyou.sms.config;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "leyou.sms")
public class SmsProperties {

    String accessKeyId;

    String accessKeySecret;

    String signName;

    String verifyCodeTemplate;

    public String getAccessKeyId() {
        return accessKeyId;
    }

    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    public String getAccessKeySecret() {
        return accessKeySecret;
    }

    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }

    public String getSignName() {
        return signName;
    }

    public void setSignName(String signName) {
        this.signName = signName;
    }

    public String getVerifyCodeTemplate() {
        return verifyCodeTemplate;
    }

    public void setVerifyCodeTemplate(String verifyCodeTemplate) {
        this.verifyCodeTemplate = verifyCodeTemplate;
    }
}

 

 

5. Create a new tool class (integrated Alibaba cloud code)

package com.leyou.sms.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.leyou.sms.config.SmsProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@EnableConfigurationProperties(SmsProperties.class)
public class SmsUtils {

    @Autowired
    private SmsProperties prop;

    //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";

    static final Logger logger = LoggerFactory.getLogger(SmsUtils.class);

    public SendSmsResponse sendSms(String phone, String code, String signName, String template) 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",
                prop.getAccessKeyId(), prop.getAccessKeySecret());
        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();
        request.setMethod(MethodType.POST);
        //Required: mobile number to be sent
        request.setPhoneNumbers(phone);
        //Required: SMS signature - can be found in SMS console
        request.setSignName(signName);
        //Required: SMS template - can be found in SMS console
        request.setTemplateCode(template);
        //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\":\"" + 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("123456");

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

        logger.info("Send SMS status:{}", sendSmsResponse.getCode());
        logger.info("Send SMS message:{}", sendSmsResponse.getMessage());

        return sendSmsResponse;
    }
}

 

6. Create a new message listening class

package com.leyou.sms.listener;

import com.aliyuncs.exceptions.ClientException;
import com.leyou.sms.config.SmsProperties;
import com.leyou.sms.utils.SmsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;


import java.util.Map;

@Component
public class SmsListener {

    @Autowired
    private SmsUtils smsUtils;

    @Autowired
    private SmsProperties smsProperties;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "LEYOU.SMS.QUEUE", durable = "true"),
            exchange = @Exchange(value = "LEYOU.SMS.EXCHANGE", ignoreDeclarationExceptions = "true", type = ExchangeTypes.TOPIC),
            key = {"verifycode_sms"}
    ))
    public void sendSms(Map<String, String> msg) throws ClientException {
        if(CollectionUtils.isEmpty(msg)) {
            return;
        }
        String phone = msg.get("phone");
        String code = msg.get("code");
        if (StringUtils.isNoneBlank(phone) && StringUtils.isNoneBlank(code)) {
            this.smsUtils.sendSms(phone, code, this.smsProperties.getSignName(), this.smsProperties.getVerifyCodeTemplate());
        }
    }
}

 

 

test

 

All we have done above are producers, and there are no consumers at present. How can we know that there are no problems with producers? Look at the message queue. If the exchange switch named sms and the queue queue can already be displayed on the panel, it means our producer function is ok~

We start the project, and then we open rabbitmq's visualizer, and we find sms in the queue

If we look at the switch again, we can see that the switch has also been synchronized.

 

In the next blog, we will configure the consumers and realize the function of sending SMS completely~

345 original articles published, 162 praised, 140000 visitors+
His message board follow

Posted by gibs on Fri, 21 Feb 2020 07:31:55 -0800