本篇文件主要介绍代码实现,前置需要的步骤,比如,阿里云账号的注册、短信服务的开启等需要自己完成
一、添加依赖
首先,在 pom.xml
文件中添加阿里云短信服务的 SDK 依赖:
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.26</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>2.1.0</version>
</dependency>
二、配置阿里云短信服务信息
在 application.properties
或 application.yml
中添加阿里云短信服务的相关配置信息(填写的是自己的信息):
aliyun:
sms:
accessKeyId: LTAI5tQoPHrPDqSqjb8MbyuC
accessKeySecret: ADbKv9PT3Tvhk5ZOtFkeQ17mEPduyJ
signName: 阿里云短信测试
templateCode: SMS_154950909
regionId: cn-hangzhou
三、创建短信服务配置类
创建一个配置类来读取配置信息并创建 DefaultAcsClient
对象:
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
// 该注解表示这个类是一个配置类,Spring 容器会扫描该类,并处理其中的 @Bean 注解的方法
public class SmsConfig {
@Value("${aliyun.sms.accessKeyId}")
// 从配置文件中读取 aliyun.sms.accessKeyId 的值并注入到该变量中
private String accessKeyId;
@Value("${aliyun.sms.accessKeySecret}")
// 从配置文件中读取 aliyun.sms.accessKeySecret 的值并注入到该变量中
private String accessKeySecret;
@Value("${aliyun.sms.regionId}")
// 从配置文件中读取 aliyun.sms.regionId 的值并注入到该变量中
private String regionId;
@Bean
// 该注解表示该方法会返回一个 Spring 容器管理的 Bean 对象,可被其他组件注入使用
public IAcsClient smsClient() throws ClientException {
// 使用读取到的 regionId、accessKeyId 和 accessKeySecret 创建 DefaultProfile 实例
IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
// 使用创建的 DefaultProfile 实例创建 DefaultAcsClient 实例,作为短信服务的客户端
return new DefaultAcsClient(profile);
}
}
四、创建短信发送服务类
创建一个服务类,用于发送短信验证码:
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class SmsServiceImpl {
@Autowired
private IAcsClient smsClient;
@Value("${aliyun.sms.signName}")
// 从配置文件中读取 aliyun.sms.signName 的值并注入到该变量中
private String signName;
@Value("${aliyun.sms.templateCode}")
// 从配置文件中读取 aliyun.sms.templateCode 的值并注入到该变量中
private String templateCode;
public boolean sendSms(String phone, String code) throws ClientException {
// 创建一个 CommonRequest 对象,用于发送请求给阿里云短信服务
CommonRequest request = new CommonRequest();
// 设置请求方法为 POST
request.setMethod(MethodType.POST);
// 设置请求的域名,即阿里云短信服务的 API 地址
request.setDomain("dysmsapi.aliyuncs.com");
// 设置请求的版本,以确保使用正确的 API 版本
request.setVersion("2017-05-25");
// 设置请求的动作,这里是发送短信的动作
request.setAction("SendSms");
// 设置请求的 RegionId,一般为 cn-hangzhou
request.putQueryParameter("RegionId", "cn-hangzhou");
// 设置要发送短信的手机号码
request.putQueryParameter("PhoneNumbers", phone);
// 设置短信签名,该值是从配置文件中注入的
request.putQueryParameter("SignName", signName);
// 设置短信模板代码,该值是从配置文件中注入的
request.putQueryParameter("TemplateCode", templateCode);
// 创建一个 Map 用于存储短信模板的参数,这里存储验证码
Map<String, Object> param = new HashMap<>();
param.put("code", code);
// 将短信模板的参数转换为 JSON 字符串并添加到请求中
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));
// 使用 smsClient 发送请求,并得到响应
CommonResponse response = smsClient.getCommonResponse(request);
// 判断响应是否成功并返回结果
return response.getHttpResponse().isSuccess();
}
}
五、使用短信发送服务
在控制器或其他服务中注入 SmsService
并调用 sendSms
方法发送短信:
@RestController
@RequestMapping("/sms")
public class SmsController {
@Autowired
private SmsService smsService;
@GetMapping("/send")
public String sendSms(@RequestParam String phone, @RequestParam String code) {
try {
boolean success = smsService.sendSms(phone, code);
if (success) {
return "短信发送成功";
} else {
return "短信发送失败";
}
} catch (Exception e) {
return "短信发送异常:" + e.getMessage();
}
}
}
六、运行和测试
- 确保你已经将
LTAI5tQoPHrPDqSqjb8MbyuC
和ADbKv9PT3Tvhk5ZOtFkeQ17mEPduyJ
替换为你自己的阿里云AccessKeyId
和AccessKeySecret
。 - 运行 Spring Boot 应用程序,使用 Postman 等工具发送请求进行测试。