Spring Boot整合阿里云SMS短信服务实现高效通信
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
public class SmsUtil {
public static SendSmsResponse sendSms(String phoneNumber, String templateCode, String signName, String templateParam) throws ClientException {
// 设置超时时间-可自行调整
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
// 初始化acsClient,核心客户端
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", "<yourAccessKeyId>", "<yourAccessKeySecret>");
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
IAcsClient acsClient = new DefaultAcsClient(profile);
// 组装请求对象-具体的短信发送请求
SendSmsRequest request = new SendSmsRequest();
// 必填: 短信接收号码
request.setPhoneNumbers(phoneNumber);
// 必填: 短信签名
request.setSignName(signName);
// 必填: 短信模板CODE
request.setTemplateCode(templateCode);
// 必填: 短信模板变量对应的实际值,JSON格式
request.setTemplateParam(templateParam);
// 发送短信
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
return sendSmsResponse;
}
}
在这个代码实例中,我们首先设置了客户端的超时时间,然后初始化了阿里云短信服务的客户端,并组装了发送短信的请求对象。最后,我们通过acsClient.getAcsResponse(request)
发送短信,并返回发送短信的响应对象。这个简单的实例展示了如何在Spring Boot应用中整合阿里云短信服务发送短信的基本过程。
评论已关闭