springboot+redis+阿里云短信實現(xiàn)手機(jī)號登錄功能
Springboot+Redis實現(xiàn)短信驗證碼發(fā)送功能
1.準(zhǔn)備工作
1.1安裝Redis
如果是開始學(xué)習(xí)的話建議安裝到自己本機(jī)環(huán)境下,Redis安裝
1.2 準(zhǔn)備一個阿里云賬戶
這里以阿里云為例
登錄到阿里云平臺后獲取AccessKey


創(chuàng)建用戶組和用戶(記得用戶創(chuàng)建完成后保存用戶信息后面會用到,切記一定一定一定要保存好用戶信息,防止泄露)


添加短信服務(wù)權(quán)限


開通阿里云短信服務(wù)在短信服務(wù)控制臺添加短信服務(wù)簽名、模板,等待審核完成即可
2.創(chuàng)建工程
創(chuàng)建Springboot項目這里jdk版本為1.8,添加以下依賴即可

2.修改pom文件
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.6.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.4</version>
</dependency>3.配置yml文件
server:
port: 8080
spring:
redis:
host: localhost
port: 6379
aliyun:
accessKeyID: 自己的accessKeyID
accessKeySecret: 自己的accessKeySecret4.測試,可以打開test測試一下是否可以發(fā)送成功,直接復(fù)制到IDEA中,修改部分參數(shù)即可進(jìn)行測試
import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.HashMap;
import java.util.Map;
@SpringBootTest
class SmsApplicationTests {
@Test
void sendSms() {
// 指定地域名稱 短信API的就是 cn-hangzhou 不能改變 后邊填寫您的 accessKey 和 accessKey Secret
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "accessKey", "accessKey Secret");
IAcsClient client = new DefaultAcsClient(profile);
// 創(chuàng)建通用的請求對象
CommonRequest request = new CommonRequest();
// 指定請求方式
request.setMethod(MethodType.POST);
// 短信api的請求地址 固定
request.setDomain("dysmsapi.aliyuncs.com");
// 簽名算法版本 固定
request.setVersion("2017-05-25");
//請求 API 的名稱。
request.setAction("SendSms");
// 上邊已經(jīng)指定過了 這里不用再指定地域名稱
//request.putQueryParameter("RegionId", "cn-hangzhou");
// 您的申請簽名
request.putQueryParameter("SignName", "自己的簽名");
// 您申請的模板 code
request.putQueryParameter("TemplateCode", "模板號");
// 要給哪個手機(jī)號發(fā)送短信 指定手機(jī)號
request.putQueryParameter("PhoneNumbers", "用于測試的手機(jī)號");
// 創(chuàng)建參數(shù)集合
Map<String, Object> params = new HashMap<>();
// 生成短信的驗證碼
String code = String.valueOf(Math.random()).substring(3, 9);
// 這里的key就是短信模板中的 ${xxxx}
params.put("code", code);
// 放入?yún)?shù) 需要把 map轉(zhuǎn)換為json格式 使用fastJson進(jìn)行轉(zhuǎn)換
request.putQueryParameter("TemplateParam", JSON.toJSONString(params));
try {
// 發(fā)送請求 獲得響應(yīng)體
CommonResponse response = client.getCommonResponse(request);
// 打印響應(yīng)體數(shù)據(jù)
System.out.println(response.getData());
// 打印 請求狀態(tài) 是否成功
System.out.println(response.getHttpResponse().isSuccess());
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
}
}
5.測試通過后就可以進(jìn)行業(yè)務(wù)層的實現(xiàn)了
項目結(jié)構(gòu)如下

3.代碼實現(xiàn)
3.1 service層
創(chuàng)建一個SendSmsService接口用于對外提供方法
public interface SendSmsService {
/**
* 發(fā)送驗證碼
* @param phoneNum 手機(jī)號
* @param code 驗證碼
* @return
*/
boolean sendSms(String phoneNum,String code);
}實現(xiàn)SendSmsService接口
import com.alibaba.fastjson.JSON;
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.aliyuncs.profile.DefaultProfile;
import com.example.sms.service.SendSmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class SendSmsServiceImp implements SendSmsService {
private static final Logger LOGGER= LoggerFactory.getLogger(SendSmsServiceImp.class);
//采用注入的方式傳遞參數(shù)
@Value("${aliyun.accessKeyID}")
private String accessKeyID;
@Value("${aliyun.accessKeySecret}")
private String accessKeySecret;
@Override
public boolean sendSms(String phoneNum, String code) {
DefaultProfile profile=DefaultProfile.getProfile("cn-hangzhou", accessKeyID,accessKeySecret);
IAcsClient client=new DefaultAcsClient(profile);
CommonRequest request=new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
request.putQueryParameter("RegionId", "cn-hangzhou");
request.putQueryParameter("SignName", "自己的簽名");
request.putQueryParameter("PhoneNumbers", phoneNum);
request.putQueryParameter("TemplateCode", "模板號");
Map<String,Object> param=new HashMap<>();
param.put("code", code);
request.putQueryParameter("TemplateParam", JSON.toJSONString(param));
try {
CommonResponse response=client.getCommonResponse(request);
//System.out.println(response.getData());//返回的消息
LOGGER.info(JSON.parseObject(response.getData(), Map.class).get("Message").toString());
return response.getHttpResponse().isSuccess();
} catch (ClientException e) {
e.printStackTrace();
}
return false;
}
}3.2 controller層
import com.aliyuncs.utils.StringUtils;
import com.example.sms.service.SendSmsService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
@RestController
@CrossOrigin//跨域支持
public class SendSmsController {
@Resource
private SendSmsService sendSmsService;
@Resource
private RedisTemplate redisTemplate;
@GetMapping("/sendSms")
public String sendSms(@RequestParam("phoneNum")String phoneNum){
//獲取到操作String的對象
ValueOperations<String,String> value = redisTemplate.opsForValue();
//根據(jù)手機(jī)號查詢
String phone = value.get(phoneNum);
//如果手機(jī)號在redis中不存在的話才進(jìn)行驗證碼的發(fā)送
if (StringUtils.isEmpty(phone)){
//生成6位隨機(jī)數(shù)
String code = String.valueOf(Math.random()).substring(3, 9);
//調(diào)用業(yè)務(wù)層
boolean sendSmsFlag = sendSmsService.sendSms(phoneNum, code);
if (sendSmsFlag){
// 發(fā)送成功之后往redis中存入該手機(jī)號以及驗證碼 并設(shè)置超時時間 5 分鐘
redisTemplate.opsForValue().set(phoneNum,code, 5, TimeUnit.MINUTES);
}
return "發(fā)送驗證碼到:" + phoneNum + "成功! " + "Message:" + sendSmsFlag;
}else {
return "該手機(jī)號:" + phoneNum + " 剩余:" + redisTemplate.getExpire(phoneNum) + "秒后可再次進(jìn)行發(fā)送!";
}
}
@GetMapping("/checkCode/{key}/[code]")
public String checkCode(@PathVariable("key") String number,
@PathVariable("code")String code){
//獲取到操作String的對象
ValueOperations<String,String> value = redisTemplate.opsForValue();
//根據(jù)key值查詢
String redisCode = value.get(number);
if (code.equals(redisCode)){
return "成功";
}
return redisCode==null ? "請先獲取驗證碼在進(jìn)行校驗!" : "錯誤";
}
}4. 測試
由于沒有前端頁面,我們借助postman工具來進(jìn)行發(fā)送驗證碼功能

此時手機(jī)上收到的驗證碼

redis中的數(shù)據(jù)

以上便是一個簡單的短信驗證碼的發(fā)送實現(xiàn),注意一定一定一定要保護(hù)好自己的AccessKey
源碼:gitee倉庫
到此這篇關(guān)于springboot+redis+阿里云短信實現(xiàn)手機(jī)號登錄的文章就介紹到這了,更多相關(guān)springboot redis阿里云短信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
kafka運(yùn)維consumer-groups.sh消費(fèi)者組管理
這篇文章主要為大家介紹了kafka運(yùn)維consumer-groups.sh消費(fèi)者組管理,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
Java結(jié)合Swing實現(xiàn)龍年祝福語生成工具
Swing是一個為Java設(shè)計的GUI工具包,屬于Java基礎(chǔ)類的一部分,本文將使用Java和Swing實現(xiàn)龍年祝福語生成工具,感興趣的小伙伴可以了解下2024-01-01
spring(java,js,html) 截圖上傳圖片實例詳解
這篇文章主要介紹了spring(java,js,html) 截圖上傳圖片實例詳解的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-07-07
Struts2中validate數(shù)據(jù)校驗的兩種方法詳解附Struts2常用校驗器
這篇文章主要介紹了Struts2中validate數(shù)據(jù)校驗的兩種方法及Struts2常用校驗器,本文介紹的非常詳細(xì),具有參考借鑒價值,感興趣的朋友一起看看吧2016-09-09
java+jsp+struts2實現(xiàn)發(fā)送郵件功能
這篇文章主要為大家詳細(xì)介紹了java+jsp+struts2實現(xiàn)發(fā)送郵件功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03
java調(diào)用文心一言API的方法實現(xiàn)過程
Java是一種廣泛使用的編程語言,用于開發(fā)各種應(yīng)用程序,下面這篇文章主要給大家介紹了關(guān)于java調(diào)用文心一言API的方法實現(xiàn),文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12
SpringBoot如何監(jiān)聽redis?Key變化事件案例詳解
項目中需要監(jiān)聽redis的一些事件比如鍵刪除,修改,過期等,下面這篇文章主要給大家介紹了關(guān)于SpringBoot如何監(jiān)聽redis?Key變化事件的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08

