短信服务的搭建代码

短信服务模块:

在这里插入图片描述

pom

 <artifactId>ly-sms</artifactId>

    <dependencies>

        <!--springboot的web的支持-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--rabbitMQ消息队列支持-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <!--测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <!--阿里云短信的支持-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.1.1</version>
        </dependency>

        <!--工具类支持-->
        <dependency>
            <groupId>com.leyou</groupId>
            <artifactId>ly-common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
    <!--打包springboot插件-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

application.yml

server:
  port: 8086
spring:
  application:
    name: sms-service
  rabbitmq:
    host: 127.0.0.1
    username: lyou116
    password: lyou
    virtual-host: /lyou116  # 队列名称
# 阿里云短信服务配置
ly:
  sms:
    accessKey: LTAI4Fd2VpKsDUa3MuH # 阿里云创建的子账号
    accessKeySecret: hU0f5OL9HjsQmP6tccFfHZAhBb
    signName: 乐优平台 # 签名名称
    verifyCodeTemplate: SMS_17653921 # 模板名称
    domain: dysmsapi.aliyuncs.com # 域名
    action: SendSMS # API类型,发送短信
    version: 2017-05-25 # API版本,固定值
    regionID: cn-hangzhou # 区域id

配置文件 属性的解析


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

/**
 *  配置文件 属性的解析
 */
@Data
@ConfigurationProperties(prefix = "ly.sms")
public class SmsProperties {
    /**
     * 账号
     */
    String accessKey;
    /**
     * 密钥
     */
    String accessKeySecret;
    /**
     * 短信签名
     */
    String signName;
    /**
     * 短信模板
     */
    String verifyCodeTemplate;
    /**
     * 发送短信请求的域名
     */
    String domain;
    /**
     * API版本
     */
    String version;
    /**
     * API类型
     */
    String action;
    /**
     * 区域
     */
    String regionID;

}

加载配置文件到IOC容器

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 配置文件 属性启动放入到IOC容器中
 */
@Configuration
@EnableConfigurationProperties(SmsProperties.class)
public class SmsConfiguration {

    @Autowired
    private SmsProperties prop;

    @Bean
    public IAcsClient acsClient(){
        DefaultProfile profile = DefaultProfile.getProfile(
                prop.getRegionID(),  // 所在区域
                prop.getAccessKey(), // 账号名称
                prop.getAccessKeySecret()  // 秘钥
        );
        return new DefaultAcsClient(profile);
    }
}

发送短信工具类


import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 发送短信 工具类
 */
@Slf4j
@Component
public class SendCheckCodeUtils {

    @Autowired
    private IAcsClient client;

    @Autowired
    private SmsProperties prop;

    /**
     *  短信发送
     * @param phone  电话号码
     * @param code   短信验证码
     */
    public void sendCodeMsg(String phone, String code) {

        CommonRequest request = new CommonRequest();

        request.setMethod(MethodType.POST);  // 请求方式
        request.setDomain(prop.getDomain()); // 域名
        request.setVersion(prop.getVersion());  // API版本
        request.setAction(prop.getAction());  // API类型,发送短信

        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_REGION_ID,prop.getRegionID()); // 区域的id名称和值
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_PHONE,phone);  // 电话号码名称和值
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_SIGN_NAME,prop.getSignName()); //  短信签名的名称和值
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_TEMPLATE_CODE,prop.getVerifyCodeTemplate()); // 发送的短信模板名称
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_TEMPLATE_PARAM,"{\"code\":\""+code+"\"}"); // 发送的短信验证码

        try {
            CommonResponse response = client.getCommonResponse(request);

            // 1、处理返回结果  调用工具类转换成map集合
            Map<String,String> repsData = JsonUtils.toMap(response.getData(),String.class,String.class);

            // 2、如果获取到的响应信息  验证码没有 打印异常信息,否则就接收验证码成功
            if (!StringUtils.equals(repsData.get(SmsConstants.SMS_RESPONSE_KEY_CODE),SmsConstants.OK)){
                log.error("手机号:"+phone+",接收短信验证码失败!原因为:"+repsData.get(SmsConstants.SMS_RESPONSE_KEY_MESSAGE));
            }
            log.info("手机号:"+phone+",接收短信验证码成功");

        } catch (ServerException e) {
            log.error("阿里云短信服务器异常!");
            e.printStackTrace();

        } catch (ClientException e) {
            log.error("本地阿里云短信客户端异常!");
            e.printStackTrace();
        }
    }

}

提取所有阿里云工具类中的key


/**
 * 提取所有阿里云工具类中的key
 */
public class SmsConstants {
    /**
     * 请求参数
     */
    public static final String SMS_PARAM_KEY_REGION_ID = "RegionId";   // 区域ID
    public static final String SMS_PARAM_KEY_PHONE = "PhoneNumbers";  // 电话号码
    public static final String SMS_PARAM_KEY_SIGN_NAME = "SignName";  // 短信签名
    public static final String SMS_PARAM_KEY_TEMPLATE_CODE = "TemplateCode";  // 发送的短信模板名称
    public static final String SMS_PARAM_KEY_TEMPLATE_PARAM= "TemplateParam";  // 发送的验证码

    /**
     * 响应结果
     */
    public static final String SMS_RESPONSE_KEY_CODE = "Code";  // 短信验证码发送错误
    public static final String SMS_RESPONSE_KEY_MESSAGE = "Message"; // 错误的信息

    /**
     * 状态
     */
    public static final String OK = "OK";
}

RabbitMQ消息队列 短信信息的监听

import lombok.extern.slf4j.Slf4j;
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 java.util.Map;

/**
 * RabbitMQ消息队列  短信信息的 监听
 */
@Slf4j
@Component
public class SmsListener {

    @Autowired
    private SendCheckCodeUtils checkCodeUtils;

    /**
     * 发送阿里云短信
     */
    @RabbitListener(bindings = @QueueBinding(
            // 监听的队列  并且创建队列, 开启持久化
            value = @Queue(value = MQConstants.Queue.SMS_VERIFY_CODE_QUEUE,durable = "true"),
            // 交换机的名称
            exchange = @Exchange(value = MQConstants.Exchange.SMS_EXCHANGE_NAME,type = ExchangeTypes.TOPIC),
            // 发送的验证码信息
            key = MQConstants.RoutingKey.VERIFY_CODE_KEY
    ))
    public void sendCheckCodeMsg(Map<String,String> codeMap){
        try {
            // 监听 获取到电话号码和短信验证码
            String phone = codeMap.get("phone");
            String code = codeMap.get("code");
            // 调用方法 发送短信
            checkCodeUtils.sendCodeMsg(phone,code);
        }catch (Exception e){
            // 消息队列发送失败
            log.error("MQ发送短信验证码失败!异常信息:{}",e);

        }
    }

}

短信服务的启动类


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

/**
 * 短信 服务
 */
@SpringBootApplication
public class LySmsApplication {
    public static void main(String[] args) {
        SpringApplication.run(LySmsApplication.class,args);
    }

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值