SpringBoot整合阿里云短信服務(wù)的案例代碼
1. 準(zhǔn)備工作
- 注冊(cè)阿里云賬號(hào):首先確保你有一個(gè)阿里云賬號(hào),并且已經(jīng)開通了短信服務(wù)。
- 獲取AccessKey ID和AccessKey Secret:在阿里云控制臺(tái)的安全管理頁(yè)面創(chuàng)建AccessKey,這是訪問(wèn)阿里云API的憑證。
- 申請(qǐng)短信簽名和模板:在阿里云短信服務(wù)控制臺(tái)申請(qǐng)短信簽名和短信模板,簽名用于標(biāo)識(shí)發(fā)送者的身份,模板用于定義短信內(nèi)容,需要審核通過(guò)才能使用。
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初始化賬號(hào)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()); // 訪問(wèn)的域名 config.endpoint = "dysmsapi.aliyuncs.com"; return new com.aliyun.dysmsapi20170525.Client(config); } }
5. 創(chuàng)建服務(wù)類
創(chuàng)建一個(gè)服務(wù)類來(lái)封裝發(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ī)號(hào)上限1000 if (mobiles.size()>1000){ throw new BaseException(ResultCode.EM_SMS_MAX_LIMIT); } //檢驗(yàn)手機(jī)號(hào)格式 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ī)號(hào)列表 * @param message json格式的模板參數(shù) * @param code 阿里云短信模板code * @return * @throws Exception */ private SendSmsResponse sendALiYunSms(String mobiles,String message,String code) throws Exception { //初始化Client對(duì)象 Client client = aliYunSmsConfig.createClient(); //構(gòu)建請(qǐng)求參數(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ù)超過(guò)限制 EM_SMS_MAX_LIMIT("10001","短信發(fā)送次數(shù)超過(guò)限制"), //無(wú)效的手機(jī)號(hào)碼 EM_SMS_INVALID_MOBILE("10002","無(wú)效的手機(jī)號(hào)碼"); @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í)行錯(cuò)誤 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 = "單個(gè)手機(jī)號(hào)發(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ā)送成功"; } }
請(qǐng)確保替換成你自己的AccessKey信息、簽名、模板CODE等,以及根據(jù)實(shí)際情況調(diào)整參數(shù)。此外,考慮到安全性,不要直接在版本控制系統(tǒng)中提交敏感信息,如AccessKey ID和AccessKey Secret,應(yīng)使用環(huán)境變量或外部配置管理服務(wù)來(lái)管理這些信息。
8.測(cè)試短信
到此這篇關(guān)于SpringBoot整合阿里云短信服務(wù)的文章就介紹到這了,更多相關(guān)SpringBoot阿里云短信服務(wù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot消息國(guó)際化配置實(shí)現(xiàn)過(guò)程解析
這篇文章主要介紹了SpringBoot消息國(guó)際化配置實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07使用Mybatis時(shí)SqlSessionFactory對(duì)象總是報(bào)空指針
本文主要介紹了使用Mybatis時(shí)SqlSessionFactory對(duì)象總是報(bào)空指針,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-09-09Spring aop 如何通過(guò)獲取代理對(duì)象實(shí)現(xiàn)事務(wù)切換
這篇文章主要介紹了Spring aop 如何通過(guò)獲取代理對(duì)象實(shí)現(xiàn)事務(wù)切換的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07Java設(shè)計(jì)模式中單一職責(zé)原則詳解
這篇文章主要介紹了Java設(shè)計(jì)模式中單一職責(zé)原則詳解,單一職責(zé)原則 (SRP) 是軟件設(shè)計(jì)中的一個(gè)重要原則,它要求每個(gè)類只負(fù)責(zé)一個(gè)職責(zé),需要的朋友可以參考下2023-05-05IntelliJ?IDEA的代碼擱置功能實(shí)現(xiàn)
本文主要介紹了IntelliJ?IDEA的代碼擱置功能實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01