springboot+redis+阿里云短信實(shí)現(xiàn)手機(jī)號登錄功能
Springboot+Redis實(shí)現(xiàn)短信驗(yàn)證碼發(fā)送功能
1.準(zhǔn)備工作
1.1安裝Redis
如果是開始學(xué)習(xí)的話建議安裝到自己本機(jī)環(huán)境下,Redis安裝
1.2 準(zhǔn)備一個(gè)阿里云賬戶
這里以阿里云為例
登錄到阿里云平臺后獲取AccessKey
創(chuàng)建用戶組和用戶(記得用戶創(chuàng)建完成后保存用戶信息后面會用到,切記一定一定一定要保存好用戶信息,防止泄露)
添加短信服務(wù)權(quán)限
開通阿里云短信服務(wù)在短信服務(wù)控制臺添加短信服務(wù)簽名、模板,等待審核完成即可
2.創(chuàng)建工程
創(chuàng)建Springboot項(xiàng)目這里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: 自己的accessKeySecret
4.測試,可以打開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", "模板號"); // 要給哪個(gè)手機(jī)號發(fā)送短信 指定手機(jī)號 request.putQueryParameter("PhoneNumbers", "用于測試的手機(jī)號"); // 創(chuàng)建參數(shù)集合 Map<String, Object> params = new HashMap<>(); // 生成短信的驗(yàn)證碼 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ù)層的實(shí)現(xiàn)了
項(xiàng)目結(jié)構(gòu)如下
3.代碼實(shí)現(xiàn)
3.1 service層
創(chuàng)建一個(gè)SendSmsService
接口用于對外提供方法
public interface SendSmsService { /** * 發(fā)送驗(yàn)證碼 * @param phoneNum 手機(jī)號 * @param code 驗(yàn)證碼 * @return */ boolean sendSms(String phoneNum,String code); }
實(shí)現(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)行驗(yà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ī)號以及驗(yàn)證碼 并設(shè)置超時(shí)時(shí)間 5 分鐘 redisTemplate.opsForValue().set(phoneNum,code, 5, TimeUnit.MINUTES); } return "發(fā)送驗(yàn)證碼到:" + 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 ? "請先獲取驗(yàn)證碼在進(jìn)行校驗(yàn)!" : "錯(cuò)誤"; } }
4. 測試
由于沒有前端頁面,我們借助postman工具來進(jìn)行發(fā)送驗(yàn)證碼功能
此時(shí)手機(jī)上收到的驗(yàn)證碼
redis中的數(shù)據(jù)
以上便是一個(gè)簡單的短信驗(yàn)證碼的發(fā)送實(shí)現(xiàn),注意一定一定一定要保護(hù)好自己的AccessKey
源碼:gitee倉庫
到此這篇關(guān)于springboot+redis+阿里云短信實(shí)現(xiàn)手機(jī)號登錄的文章就介紹到這了,更多相關(guān)springboot redis阿里云短信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot基于Redis實(shí)現(xiàn)短信登錄的操作
- SpringBoot下token短信驗(yàn)證登入登出權(quán)限操作(token存放redis,ali短信接口)
- SpringSecurity整合springBoot、redis實(shí)現(xiàn)登錄互踢功能
- SpringBoot+SpringSession+Redis實(shí)現(xiàn)session共享及唯一登錄示例
- SpringBoot+Vue+Redis實(shí)現(xiàn)單點(diǎn)登錄(一處登錄另一處退出登錄)
- 基于springboot和redis實(shí)現(xiàn)單點(diǎn)登錄
相關(guān)文章
使用SpringBoot+OkHttp+fastjson實(shí)現(xiàn)Github的OAuth第三方登錄
這篇文章主要介紹了使用SpringBoot+OkHttp+fastjson實(shí)現(xiàn)Github的OAuth第三方登錄,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02解決logback-classic 使用testCompile的打包問題
這篇文章主要介紹了解決logback-classic 使用testCompile的打包問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07SpringCloud創(chuàng)建多模塊項(xiàng)目的實(shí)現(xiàn)示例
,Spring Cloud作為一個(gè)強(qiáng)大的微服務(wù)框架,提供了豐富的功能和組件,本文主要介紹了SpringCloud創(chuàng)建多模塊項(xiàng)目的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下2024-02-02如何解決報(bào)錯(cuò):java.net.BindException:無法指定被請求的地址問題
在Linux虛擬機(jī)上安裝并啟動(dòng)Tomcat時(shí)遇到啟動(dòng)失敗的問題,通過檢查端口及配置文件未發(fā)現(xiàn)異常,后發(fā)現(xiàn)/etc/hosts文件中缺少localhost的映射,添加后重啟Tomcat成功,Tomcat啟動(dòng)時(shí)會檢查localhost的IP映射,缺失或錯(cuò)誤都可能導(dǎo)致啟動(dòng)失敗2024-10-10java isInterrupted()判斷線程的實(shí)例講解
在本篇內(nèi)容里小編給大家分享的是一篇關(guān)于java isInterrupted()判斷線程的實(shí)例講解內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2021-05-05