官方定义:
短信服务(Short Message Service)是指通过调用短信发送API,将指定短信内容发送给指定用户。用户收到的短信来自106开头的号码,短信的内容多用于企业向用户传递验证码、系统通知、会员服务等。
导入相关依赖:
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.1</version>
</dependency>
配置类:
@Data
@ConfigurationProperties(prefix="tanhua.sms")
public class SmsProperties(){
private String signName;
private String templateCode;
private String accessKey;
private String secret;
}
发送短信模板对象:
package com.tanhua.autoconfig.template;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.tanhua.autoconfig.properties.SmsProperties;
/**
* @Author zzw2000
* @Date 2022年04月10日 23:05
* @Description 发送短信模板对象
*/
public class SmsTemplate(){
private SmsProperties properties;
public SmsTemplate(SmsProperties properties){
this.properties=properties;
}
public void sendSms(){
try{
//配置阿里云
Config config = new Config()
.setAccessKeyId(properties.getAccessKey()) //您的AccessKey ID
.setAccessKeySecret(properties.getSecret()); // 您的AccessKey Secret
// 访问的域名
config.endpoint = "dysmsapi.aliyuncs.com";
com.aliyun.dysmsapi20170525.Client client = new com.aliyun.dysmsapi20170525.Client(config);
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setPhoneNumbers(mobile)
.setSignName(properties.getSignName())
.setTemplateCode(properties.getTemplateCode())
.setTemplateParam("{\"code\":\""+code+"\"}");
// 复制代码运行请自行打印 API 的返回值
SendSmsResponse response = client.sendSms(sendSmsRequest);
SendSmsResponseBody body = response.getBody();
System.out.println(body.getMessage());
}catch(Exception e){
e.printStackTrace();
}
}
}
自动装配类:
package com.tanhua.autoconfig;
import com.tanhua.autoconfig.properties.SmsProperties;
import com.tanhua.autoconfig.template.SmsTemplate;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
/**
* @Author zzw2000
* @Date 2022年04月10日 23:12
* @Description 自动装配类
*/
@EnableConfigurationProperties({SmsProperties.class})
public class TanhuaAutoConfiguration{
@Bean
public SmsTemplate smsTemplate(SmsProperties properties){
return new SmsTemplate(properties);
}
}
自动装配配置:
根据自动装配原则,在tanhua-autoconfig工程resources目录下创建/META-INF/spring.factories文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.tanhua.autoconfig.TanhuaAutoConfiguration
在application.yml中添加短信配置:
tanhua:
sms:
signName: 您的签名名称
templateCode: 模板代码
accessKey: 密钥ID
secret: 密钥密码