最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot+redis+阿里云短信實現(xiàn)手機(jī)號登錄功能

 更新時間:2024年01月03日 10:15:27   作者:小 王  
這篇文章主要介紹了springboot+redis+阿里云短信實現(xiàn)手機(jī)號登錄功能,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

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: 自己的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", "模板號");
        // 要給哪個手機(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)文章

最新評論

丽水市| 沾化县| 仁布县| 伊宁县| 宝清县| 浦县| 新兴县| 崇明县| 梓潼县| 中阳县| 永昌县| 汽车| 夏邑县| 平山县| 新源县| 汤原县| 天水市| 兖州市| 新晃| 太原市| 通许县| 克什克腾旗| 读书| 兴宁市| 绍兴市| 公主岭市| 沂源县| 林州市| 南投市| 宜良县| 南京市| 克拉玛依市| 汉源县| 文安县| 阿鲁科尔沁旗| 敦化市| 普洱| 灯塔市| 六安市| 桓台县| 镇平县|