项目目录
二、配置阿里云com.aliyun aliyun-java-sdk-core 4.0.6 com.aliyun aliyun-java-sdk-dysmsapi 1.1.0
在 resources 目录下新建配置文件 oss-conf.properties
# 阿里云配置 # 配置自己的accessKeyId aliyun.access-key-id=xxxx # 配置自己的accessKeySecret aliyun.access-key-secret=xxxx三、添加配置类
添加配置类 AliYunProperties
@Data
@ConfigurationProperties(prefix = "aliyun")
@PropertySource(value = {"classpath:oss-conf.properties"}, encoding = "UTF-8")
public class AliYunProperties {
private String accessKeyId;
private String accessKeySecret;
}
四、激活配置类
新建配置类 EnableConfig
@Configuration
@EnableConfigurationProperties({AliYunOssProperties.class, AliYunProperties.class})
@EnableRetry
public class EnableConfig {
}
五、添加 AliYunSmsService
添加类 AliYunSmsService 和 AliYunSmsServiceImpl
public interface AliYunSmsService {
Boolean sendSms(String phone);
}
@Service
@Slf4j
@RequiredArgsConstructor
public class AliYunSmsServiceImpl implements AliYunSmsService {
private final AliYunProperties aliYunProperties;
@Override
public Boolean sendSms(String phone) {
// 短信API产品名称(无需修改)
final String product = "Dysmsapi";
// 短信API产品域名(无需修改)
final String domain = "dysmsapi.aliyuncs.com";
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",
aliYunProperties.getAccessKeyId(),
aliYunProperties.getAccessKeySecret());
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
IAcsClient acsClient = new DefaultAcsClient(profile);
SendSmsRequest sendSmsRequest = getSendSmsRequest(phone);
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(sendSmsRequest);
log.info("[发送短信]phone={}, result={}", phone, sendSmsResponse.getCode());
return sendSmsResponse.getCode() != null && "OK".equals(sendSmsResponse.getCode());
}
private SendSmsRequest getSendSmsRequest(String phone) {
SendSmsRequest request = new SendSmsRequest();
request.setMethod(MethodType.POST);
// 多个手机号逗号分割 上限1000个
request.setPhoneNumbers(phone);
// 短信签名(替换自己的签名)
request.setSignName("连连商城");
// 短信模板(替换自己的模板)
request.setTemplateCode("SMS_222860055");
request.setTemplateParam("{"code": "" + getCode() + ""}");
return request;
}
public String getCode() {
Random random = new Random();
StringBuilder result = new StringBuilder();
for (int i = 0; i < 6; i++) {
result.append(random.nextInt(10));
}
return result.toString();
}
}
至此,就可以使用 AliYunSmsService 来发送短信了!!
六、测试新建一个 Controller 来测试一下
使用 Postman 发送请求
发送成功



