飞道的博客

SpringCloud搭建短信微服务

428人阅读  评论(0)

开通阿里短信服务

依赖坐标

    <dependencies>
        <!--web起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--单元测试依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--阿里云的SDK依赖-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.1.1</version>
        </dependency>
    </dependencies>

编写启动类



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

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

编写application.yml配置文件

server:
  port: 8086
spring:
  application:
    name: sms-service

封装短信工具

阿里云官方测试发送短信类

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;
/*
pom.xml
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>4.0.3</version>
</dependency>
*/
public class SendSms {
    public static void main(String[] args) {
   
        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", "xxx");
        request.putQueryParameter("SignName", "xxx");
        request.putQueryParameter("TemplateCode", "xxx");
        request.putQueryParameter("TemplateParam", "{\"checkcode\":\"666\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}

我们需要进行对该类改造往后便于维护

  • 抽取属性
ly:
  sms:
    accessKeyID: LTAIfmmL26haCK0b # 你自己的accessKeyId
    accessKeySecret: pX3RQns9ZwXs75M6Isae9sMgBLXDfY # 你自己的AccessKeySecret
    signName: 签名名称 # 签名名称
    verifyCodeTemplate: SMS_133976814 # 模板名称
    domain: dysmsapi.aliyuncs.com # 域名
    action: SendSMS # API类型,发送短信
    version: 2017-05-25 # API版本,固定值
    regionID: cn-hangzhou # 区域id
    code: code # 短信模板中验证码的占位符
  • 然后提供解析配置文件的配置类
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

@Data
@ConfigurationProperties(prefix = "ly.sms")  //读取配置文件的配置到本类属性中
public class SmsProperties {
    String accessKeyID; //账号
    String accessKeySecret;//密钥
    String signName;//短信签名
    String verifyCodeTemplate;//短信模板
    String domain;//发送短信请求的域名
    String version;//API版本
    String action;//API类型
    String regionID;//区域
    String code; // 短信验证码的占位符
}
  • 参数Key的静态变量
public final class SmsConstants {

    /**
     * 请求参数
     */
    public static final String SMS_PARAM_REGION_ID = "RegionId";
    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";
}
  • 由于每次发送短信都需要调用阿里客户端
  DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "<accessKeyId>", "<accessSecret>");
        //每次发送短信都需要调用阿里客户端
        IAcsClient client = new DefaultAcsClient(profile);
  • 所以我们要将阿里客户端交给spring管理
@Configuration  //该类是配置类
@EnableConfigurationProperties(SmsProperties.class)  //引入该配置类
public class SmsConfiguration {

   @Autowired
   private SmsProperties prop;

   /**
    * 由于每次发送短信都需要创建发送短信客户端,所以我们将发送短信客户端交给spring管理
    * @return
    */
   @Bean
   public IAcsClient client(){
       DefaultProfile profile = DefaultProfile.getProfile(prop.regionID, prop.accessKeyID, prop.accessKeySecret);
       IAcsClient client = new DefaultAcsClient(profile);
       return client;
   }
}

发送短信工具类

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

    //配置文件中的属性
    @Autowired
    private SmsProperties prop;

    //发送短信客户端
    @Autowired
    private IAcsClient client;



    /**
     * 用于发送短信
     *
     * @param phone  用户注册的手机号
     * @param num 手机验证码【我们系统生成】
     */
    public void sendSms(String phone, String num) {

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(prop.getDomain());
        request.setVersion(prop.getVersion());
        request.setAction(prop.getAction());
        request.putQueryParameter(SmsConstants.SMS_PARAM_REGION_ID, prop.getRegionID());
        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, "{\""+prop.getCode()+"\":\""+num+"\"}");

        //发送短信操作
		 CommonResponse response = client.getCommonResponse(request);
 
	}
}

写测试类测试就可以了


转载:https://blog.csdn.net/xiannbi/article/details/106175387
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场