SpringBoot整合阿里云短信服務(wù)的案例代碼
1. 準(zhǔn)備工作
- 注冊阿里云賬號:首先確保你有一個阿里云賬號,并且已經(jīng)開通了短信服務(wù)。
- 獲取AccessKey ID和AccessKey Secret:在阿里云控制臺的安全管理頁面創(chuàng)建AccessKey,這是訪問阿里云API的憑證。
- 申請短信簽名和模板:在阿里云短信服務(wù)控制臺申請短信簽名和短信模板,簽名用于標(biāo)識發(fā)送者的身份,模板用于定義短信內(nèi)容,需要審核通過才能使用。

2. 添加依賴
在Spring Boot項(xiàng)目的pom.xml文件中添加阿里云短信服務(wù)SDK的依賴。例如:
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.6.0</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>2.1.0</version>
</dependency>3. 配置阿里云短信服務(wù)
在application.yml或application.properties中配置AccessKey ID、AccessKey Secret以及其他可能需要的參數(shù),例如:
sms:
aliyun:
accessKeyId: your-access-key-id
accessKeySecret: your-access-key-secret
signName: ####
# 是否開啟短信服務(wù)
pushSms: true
templateCode: SMS_#########4. 創(chuàng)建配置類
package com.example.demo.config.sms;
import com.aliyun.teaopenapi.models.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author xueyaoxuan
*/
@Data
@Component
@ConfigurationProperties(prefix = "sms.aliyun")
public class AliYunSmsConfig {
private String accessKeyId;
private String accessKeySecret;
private String signName;
private boolean isPushSms;
/**
* 使用AK&SK初始化賬號Client
*
* @return Client
* @throws Exception
*/
public com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
Config config = new Config()
// AccessKey ID
.setAccessKeyId(this.getAccessKeyId())
// AccessKey Secret
.setAccessKeySecret(this.getAccessKeySecret());
// 訪問的域名
config.endpoint = "dysmsapi.aliyuncs.com";
return new com.aliyun.dysmsapi20170525.Client(config);
}
}5. 創(chuàng)建服務(wù)類
創(chuàng)建一個服務(wù)類來封裝發(fā)送短信的邏輯
package com.example.demo.sms;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.example.demo.config.sms.AliYunSmsConfig;
import com.example.demo.config.ResultCode;
import com.example.demo.exception.base.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.Collectors;
/**
* 阿里云短信服務(wù)實(shí)現(xiàn)
* @author xueyaoxuan
*/
@Slf4j
@Component
public class AliYunSmsServiceImpl implements SmsService {
@Autowired
AliYunSmsServiceImpl (AliYunSmsConfig aliYunSmsConfig) {
this.aliYunSmsConfig = aliYunSmsConfig;
}
private AliYunSmsConfig aliYunSmsConfig;
@Override
public void sendSms(List<String> mobiles, String message, String code) {
SendSmsResponse sendSmsResponse = null;
try{
//調(diào)用阿里云api手機(jī)號上限1000
if (mobiles.size()>1000){
throw new BaseException(ResultCode.EM_SMS_MAX_LIMIT);
}
//檢驗(yàn)手機(jī)號格式
mobiles.forEach(mobile->{
if (StrUtil.isAllEmpty(mobile)){
throw new BaseException(ResultCode.EM_SMS_INVALID_MOBILE);
}
});
sendSmsResponse = sendALiYunSms(mobiles.stream().collect(Collectors.joining(",")),
message, code);
log.info("阿里云短信服務(wù)響應(yīng):[{}]",JSON.toJSONString(sendSmsResponse));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 發(fā)送阿里云短信
*
* @param mobiles 手機(jī)號列表
* @param message json格式的模板參數(shù)
* @param code 阿里云短信模板code
* @return
* @throws Exception
*/
private SendSmsResponse sendALiYunSms(String mobiles,String message,String code) throws Exception {
//初始化Client對象
Client client = aliYunSmsConfig.createClient();
//構(gòu)建請求參數(shù)
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setPhoneNumbers(mobiles)
.setSignName(aliYunSmsConfig.getSignName())
.setTemplateCode(code)
.setTemplateParam(message);
//發(fā)送短信
return client.sendSms(sendSmsRequest);
}
}6.自定義異常
package com.example.demo.config;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* ResultCode : 響應(yīng)封裝實(shí)現(xiàn)類
*
* @author zyw
* @create 2023/6/15
*/
@AllArgsConstructor
@NoArgsConstructor
public enum ResultCode implements IResultCode, Serializable {
//短信發(fā)送次數(shù)超過限制
EM_SMS_MAX_LIMIT("10001","短信發(fā)送次數(shù)超過限制"),
//無效的手機(jī)號碼
EM_SMS_INVALID_MOBILE("10002","無效的手機(jī)號碼");
@Override
public String getCode() {
return code;
}
@Override
public String getMsg() {
return msg;
}
private String code;
private String msg;
@Override
public String toString() {
return "{" +
"\"code\":\"" + code + '\"' +
", \"msg\":\"" + msg + '\"' +
'}';
}
// 默認(rèn)系統(tǒng)執(zhí)行錯誤
public static ResultCode getValue(String code) {
for (ResultCode value : values()) {
if (value.getCode().equals(code)) {
return value;
}
}
return ECEPTION;
}
}7.使用服務(wù)類發(fā)送短信
在需要發(fā)送短信的地方注入SmsService并調(diào)用其方法發(fā)送短信。
package com.example.demo.controller;
import com.alibaba.fastjson.JSON;
import com.example.demo.sms.SmsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* SmsController : 短信控制器
*
* @author zyw
* @create 2024-06-11 15:56
*/
@RestController
@Tag(name = "短信控制器")
@RequestMapping("sms")
public class SmsController {
@Resource
private SmsService smsService;
@Value("${sms.aliyun.templateCode}")
private String templateCode;
//發(fā)送短信
@Operation(summary = "單個手機(jī)號發(fā)送短信驗(yàn)證碼")
@PostMapping("/SendATextMessageByhone")
public String SendATextMessageByhone(String mobile, String message) {
Map<String, String> tempContentMap = new HashMap<>();
tempContentMap.put("code", String.valueOf(message));
smsService.sendSms(List.of(mobile), JSON.toJSONString(tempContentMap), templateCode);
return "短信發(fā)送成功";
}
}請確保替換成你自己的AccessKey信息、簽名、模板CODE等,以及根據(jù)實(shí)際情況調(diào)整參數(shù)。此外,考慮到安全性,不要直接在版本控制系統(tǒng)中提交敏感信息,如AccessKey ID和AccessKey Secret,應(yīng)使用環(huán)境變量或外部配置管理服務(wù)來管理這些信息。
8.測試短信


到此這篇關(guān)于SpringBoot整合阿里云短信服務(wù)的文章就介紹到這了,更多相關(guān)SpringBoot阿里云短信服務(wù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot消息國際化配置實(shí)現(xiàn)過程解析
這篇文章主要介紹了SpringBoot消息國際化配置實(shí)現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07
使用Mybatis時SqlSessionFactory對象總是報(bào)空指針
本文主要介紹了使用Mybatis時SqlSessionFactory對象總是報(bào)空指針,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-09-09
Spring aop 如何通過獲取代理對象實(shí)現(xiàn)事務(wù)切換
這篇文章主要介紹了Spring aop 如何通過獲取代理對象實(shí)現(xiàn)事務(wù)切換的操作,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
Java設(shè)計(jì)模式中單一職責(zé)原則詳解
這篇文章主要介紹了Java設(shè)計(jì)模式中單一職責(zé)原則詳解,單一職責(zé)原則 (SRP) 是軟件設(shè)計(jì)中的一個重要原則,它要求每個類只負(fù)責(zé)一個職責(zé),需要的朋友可以參考下2023-05-05
IntelliJ?IDEA的代碼擱置功能實(shí)現(xiàn)
本文主要介紹了IntelliJ?IDEA的代碼擱置功能實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01

