springboot+redis+阿里云短信實現(xiàn)手機號登錄功能
Springboot+Redis實現(xiàn)短信驗證碼發(fā)送功能
1.準備工作
1.1安裝Redis
如果是開始學習的話建議安裝到自己本機環(huán)境下,Redis安裝
1.2 準備一個阿里云賬戶
這里以阿里云為例
登錄到阿里云平臺后獲取AccessKey
創(chuàng)建用戶組和用戶(記得用戶創(chuàng)建完成后保存用戶信息后面會用到,切記一定一定一定要保存好用戶信息,防止泄露)
添加短信服務權限
開通阿里云短信服務在短信服務控制臺添加短信服務簽名、模板,等待審核完成即可
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: 自己的accessKeySecret
4.測試,可以打開test測試一下是否可以發(fā)送成功,直接復制到IDEA中,修改部分參數(shù)即可進行測試
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", "模板號"); // 要給哪個手機號發(fā)送短信 指定手機號 request.putQueryParameter("PhoneNumbers", "用于測試的手機號"); // 創(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轉換為json格式 使用fastJson進行轉換 request.putQueryParameter("TemplateParam", JSON.toJSONString(params)); try { // 發(fā)送請求 獲得響應體 CommonResponse response = client.getCommonResponse(request); // 打印響應體數(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.測試通過后就可以進行業(yè)務層的實現(xiàn)了
項目結構如下
3.代碼實現(xiàn)
3.1 service層
創(chuàng)建一個SendSmsService
接口用于對外提供方法
public interface SendSmsService { /** * 發(fā)送驗證碼 * @param phoneNum 手機號 * @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ù)手機號查詢 String phone = value.get(phoneNum); //如果手機號在redis中不存在的話才進行驗證碼的發(fā)送 if (StringUtils.isEmpty(phone)){ //生成6位隨機數(shù) String code = String.valueOf(Math.random()).substring(3, 9); //調(diào)用業(yè)務層 boolean sendSmsFlag = sendSmsService.sendSms(phoneNum, code); if (sendSmsFlag){ // 發(fā)送成功之后往redis中存入該手機號以及驗證碼 并設置超時時間 5 分鐘 redisTemplate.opsForValue().set(phoneNum,code, 5, TimeUnit.MINUTES); } return "發(fā)送驗證碼到:" + phoneNum + "成功! " + "Message:" + sendSmsFlag; }else { return "該手機號:" + phoneNum + " 剩余:" + redisTemplate.getExpire(phoneNum) + "秒后可再次進行發(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 ? "請先獲取驗證碼在進行校驗!" : "錯誤"; } }
4. 測試
由于沒有前端頁面,我們借助postman工具來進行發(fā)送驗證碼功能
此時手機上收到的驗證碼
redis中的數(shù)據(jù)
以上便是一個簡單的短信驗證碼的發(fā)送實現(xiàn),注意一定一定一定要保護好自己的AccessKey
源碼:gitee倉庫
到此這篇關于springboot+redis+阿里云短信實現(xiàn)手機號登錄的文章就介紹到這了,更多相關springboot redis阿里云短信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用SpringBoot+OkHttp+fastjson實現(xiàn)Github的OAuth第三方登錄
這篇文章主要介紹了使用SpringBoot+OkHttp+fastjson實現(xiàn)Github的OAuth第三方登錄,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-02-02解決logback-classic 使用testCompile的打包問題
這篇文章主要介紹了解決logback-classic 使用testCompile的打包問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07SpringCloud創(chuàng)建多模塊項目的實現(xiàn)示例
,Spring Cloud作為一個強大的微服務框架,提供了豐富的功能和組件,本文主要介紹了SpringCloud創(chuàng)建多模塊項目的實現(xiàn)示例,具有一定的參考價值,感興趣的可以了解一下2024-02-02如何解決報錯:java.net.BindException:無法指定被請求的地址問題
在Linux虛擬機上安裝并啟動Tomcat時遇到啟動失敗的問題,通過檢查端口及配置文件未發(fā)現(xiàn)異常,后發(fā)現(xiàn)/etc/hosts文件中缺少localhost的映射,添加后重啟Tomcat成功,Tomcat啟動時會檢查localhost的IP映射,缺失或錯誤都可能導致啟動失敗2024-10-10