配置1
package com.wn.sms.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
/**
* @author yellow Docter
* @date 2023 -07-21
* @desc 短信的自动装配
*/
@Configuration
@EnableConfigurationProperties({SmsProperties.class}) //引入 sms的配置 添加到ioc容器中
public class SmsAutoConfiguration {
//创建对象 添加到ioc容器中
@Bean
public SmsTemplate smsTemplate(SmsProperties smsProperties) {
SmsTemplate smsTemplate = new SmsTemplate(smsProperties);
return smsTemplate;
}
}
配置2
package com.wn.sms.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author yellow Docter
* @date 2023 -07-21
* @desc
*
* ConfigurationProperties
* 这个可以 可以把 yml中的配置文件 进行读取 封装成一个对象
* prefix 前缀
* SmsProperties 类中的属性需要和 yml中的字段一致
*/
@Data
@ConfigurationProperties(prefix = "aliyun.sms")
public class SmsProperties {
private String signName;
private String templateCode;
private String accessKey;
private String secret;
}
配置3
package com.wn.sms.config;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
/**
* @author yellow Docter
* @date 2023 -07-21
* @desc
* 发送短信的模板
*/
public class SmsTemplate {
private SmsProperties smsProperties;
public SmsTemplate(SmsProperties smsProperties) {
this.smsProperties = smsProperties;
}
/**
* 发送短信的 方法
* @param phone 手机号码
* @param code 验证码
*/
public void send(String phone,String code){
// 超时时间
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
try {
//初始化acsClient,暂不支持region化
IClientProfile profile = DefaultProfile.getProfile(
"cn-hangzhou",
smsProperties.getAccessKey(), //ak
smsProperties.getSecret()); //密匙
DefaultProfile.addEndpoint("cn-hangzhou",
"cn-hangzhou",
"Dysmsapi",
"dysmsapi.aliyuncs.com");
IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象-具体描述见控制台-文档部分内容
SendSmsRequest request = new SendSmsRequest();
//必填:待发送手机号
request.setPhoneNumbers(phone);
//必填:短信签名-可在短信控制台中找到
request.setSignName(smsProperties.getSignName());
//必填:短信模板-可在短信控制台中找到
request.setTemplateCode(smsProperties.getTemplateCode());
//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
request.setTemplateParam("{\"code\":\""+code+"\"}");
//发送短信
acsClient.getAcsResponse(request);
}catch (Exception e) {
e.printStackTrace();
}
}
}
yml
aliyun: sms: signName: xxx阿里云申请签名 templateCode: 自己申请 accessKey: xxx secret: xxxx