發(fā)送短信驗證碼實現手機號碼注冊

1、用戶注冊

需求分析:注冊賬號攻锰,用手機號注冊晾嘶,填寫后發(fā)送短信驗證碼,填寫短信驗證碼正確方可注冊成 功娶吞。

2垒迂、發(fā)送短信驗證碼

2.1、實現思路

在用戶微服務編寫API 妒蛇,生成手機驗證碼机断,存入Redis并發(fā)送到RabbitMQ。

2.2绣夺、準備工作

(1)因為要用到緩存和消息隊列吏奸,所以在用戶微服務(user)引入 redis和amqp的依賴。
      <!--redis-->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-redis</artifactId>
      </dependency>
      <!--rabbitMQ-->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-amqp</artifactId>
      </dependency>
(2)修改 application.yml ,在spring 節(jié)點下添加配置
spring: 
  application:  
    name: user #指定服務名
  # redis
  redis:
    host:  56.99.xxx.xxx
  # rabbitMQ
  rabbitmq:
    host:  56.99.xxx.xxx

2.3乐导、實現代碼

(1)在UserService中新增方法,用于發(fā)送短信驗證碼
    /*
     * @Description: //TODO 發(fā)送短信
     * @Param: [mobile] mobile手機號碼
     * @return: void
     */
    public void sendSms(String mobile) {
        //生成6位數字隨機數(RandomStringUtils 為 commons-lang3 中生成隨機數方法浸颓,需引入commons-lang3依賴)
        String checkcode = RandomStringUtils.randomNumeric(6);
        //向緩存中存一份
        redisTemplate.opsForValue().set("checkcode_"+mobile, checkcode, 6, TimeUnit.HOURS);
        //給用戶發(fā)一份
        Map<String, String> map = new HashMap<>();
        map.put("mobile", mobile);
        map.put("checkcode", checkcode);
        rabbitTemplate.convertAndSend("sms", map);
        //在控制臺顯示一份【方便測試】
        System.out.println("驗證碼為:"+checkcode);
    }

commons-lang3 依賴

      <!-- commons-lang3 -->
      <dependency>
          <groupId>org.apache.commons</groupId>
          <artifactId>commons-lang3</artifactId>
      </dependency>

(2)UserController新增方法
    /*
     * @Description: //TODO 發(fā)送短信驗證碼
     * @Param: mobile 手機號碼
     * @return: 
     */
    @PostMapping("/sendsms/{mobile}")
    public Result sendSms(@PathVariable String mobile){
        userService.sendSms(mobile);
        return new Result(true, StatusCode.OK, "發(fā)送成功");
    }
(3)啟動微服務物臂,在rabbitMQ中創(chuàng)建名為sms的隊列旺拉,測試API

3、用戶注冊

(1)UserService增加方法
   /**
     * 增加
     * @param user
     */
    public void add(User user) {
        user.setId( idWorker.nextId()+"" );
        userDao.save(user);
    }
(2)UserController增加方法

    /*
     * @Description: //TODO 用戶注冊
     * @Param: [code, user]
     * @return: entity.Result
     */
    @PostMapping("/register/{code}")
    public Result regist(@PathVariable String code, @RequestBody User user){
        //得到緩存中的驗證碼
        String checkcodeRedis = (String) redisTemplate.opsForValue().get("checkcode_"+user.getMobile());
        if (checkcodeRedis.isEmpty()){
            return new Result(false, StatusCode.ERROR, "請先獲取驗證碼");
        }
        if(!checkcodeRedis.equals(code)){
            return new Result(false, StatusCode.ERROR, "驗證碼錯誤");
        }
        userService.add(user);
        return new Result(true, StatusCode.OK, "注冊成功");
    }

(3)測試

4棵磷、短信微服務

4.1 蛾狗、需求分析

?? (1)、開發(fā)短信發(fā)送微服務仪媒,從rabbitMQ中提取消息沉桌,調用阿里云短信接口實現短信發(fā)送 。
?? (2)算吩、這里實際做的就是消息的消費者.留凭。

4.2、提取隊列中的消息

4.2.1偎巢、工程搭建

(1)創(chuàng)建工程模塊:sms蔼夜,pom.xml引入依賴
      <!--rabbitMQ-->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-amqp</artifactId>
      </dependency>
(2)創(chuàng)建application.yml
server:
  port: 9009
spring:
  application:
    name: sms #微服務名稱
  rabbitmq:
    host: 56.99.xxx.xxx
(3)com.springboot.sms 包下創(chuàng)建啟動類
@SpringBootApplication
public class SmsApplication {
    public static void main(String[] args) {
        SpringApplication.run(SmsApplication.class);
    }
}

4.2.2、消息監(jiān)聽類

(1)創(chuàng)建短信監(jiān)聽類压昼,獲取手機號和驗證碼
/**
 * 短信監(jiān)聽類
 */
@Component
@RabbitListener(queues = "sms")
public class SmsListener {

    @RabbitHandler
    public void executeSms(Map<String, String> map) throws ClientException {
        String mobile = map.get("mobile");
        String checkcode = map.get("checkcode");
        System.out.println("手機號碼:"+ mobile);
        System.out.println("驗證碼:"+ checkcode);
    }
}
(2)運行SmsApplication類求冷,控制臺顯示手機號和驗證碼

4.3、 發(fā)送短信(阿里云通信)

4.3.1窍霞、準備工作

(1)在阿里云官網 www.alidayu.com 注冊賬號
(2)登陸阿里云匠题,產品中選擇”短信服務“
(3)申請簽名
(4)申請模板
(5)創(chuàng)建 accessKey (注意保密!)
(6)充值

4.3.2 代碼編寫

(1)創(chuàng)建工程模塊sms但金,pom.xml引入依賴
       <!-- 阿里云短信服務所需 -->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.0.6</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
            <version>1.1.0</version>
        </dependency>
        <!--解決報JsonParser錯-->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
(2)修改application.yml 韭山,增加配置
#阿里云短信相關
aliyun:
  sms:
    accessKeyId: 你自己的
    accessKeySecret: 你自己的
    template_code: 你自己的
    sing_name: 你自己的
(3)創(chuàng)建短信工具類SmsUtil
package com.springboot.sms.utils;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * 短信工具類
 * @author Administrator
 *
 */
@Component
public class SmsUtil {

    //產品名稱:云通信短信API產品,開發(fā)者無需替換
    static final String product = "Dysmsapi";
    //產品域名,開發(fā)者無需替換
    static final String domain = "dysmsapi.aliyuncs.com";

    @Autowired
    private Environment env;

    // TODO 此處需要替換成開發(fā)者自己的AK(在阿里云訪問控制臺尋找)

    /**
     * 發(fā)送短信
     * @param mobile 手機號
     * @param template_code 模板號
     * @param sign_name 簽名
     * @param param 參數
     * @return
     * @throws ClientException
     */
    public SendSmsResponse sendSms(String mobile,String template_code,String sign_name,String param) throws ClientException {
        String accessKeyId =env.getProperty("aliyun.sms.accessKeyId");
        String accessKeySecret = env.getProperty("aliyun.sms.accessKeySecret");
        //可自助調整超時時間
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暫不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //組裝請求對象-具體描述見控制臺-文檔部分內容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待發(fā)送手機號
        request.setPhoneNumbers(mobile);
        //必填:短信簽名-可在短信控制臺中找到
        request.setSignName(sign_name);
        //必填:短信模板-可在短信控制臺中找到
        request.setTemplateCode(template_code);
        //可選:模板中的變量替換JSON串,如模板內容為"親愛的${name},您的驗證碼為${code}"時,此處的值為
        request.setTemplateParam(param);
        //選填-上行短信擴展碼(無特殊需求用戶請忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可選:outId為提供給業(yè)務方擴展字段,最終在短信回執(zhí)消息中將此值帶回給調用者
        request.setOutId("yourOutId");
        //hint 此處可能會拋出異常,注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        return sendSmsResponse;
    }

    public  QuerySendDetailsResponse querySendDetails(String mobile,String bizId) throws ClientException {
        String accessKeyId =env.getProperty("accessKeyId");
        String accessKeySecret = env.getProperty("accessKeySecret");
        //可自助調整超時時間
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暫不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //組裝請求對象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-號碼
        request.setPhoneNumber(mobile);
        //可選-流水號
        request.setBizId(bizId);
        //必填-發(fā)送日期 支持30天內記錄查詢傲绣,格式yyyyMMdd
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        request.setSendDate(ft.format(new Date()));
        //必填-頁大小
        request.setPageSize(10L);
        //必填-當前頁碼從1開始計數
        request.setCurrentPage(1L);
        //hint 此處可能會拋出異常掠哥,注意catch
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);
        return querySendDetailsResponse;
    }
}

(4)修改消息監(jiān)聽類,完成短信發(fā)送
package com.springboot.sms.listener;

import com.aliyuncs.exceptions.ClientException;
import com.tensquare.sms.utils.SmsUtil;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Description: //TODO短信監(jiān)聽類
 */
@Component
@RabbitListener(queues = "sms")
public class SmsListener {

    @Autowired
    private SmsUtil smsUtil;

    @Autowired
    private Environment env;

    @RabbitHandler
    public void executeSms(Map<String, String> map) throws ClientException {
        String mobile = map.get("mobile");
        String checkcode = map.get("checkcode");
        String template_code = env.getProperty("aliyun.sms.template_code");
        String sing_name = env.getProperty("aliyun.sms.sing_name");

        System.out.println("手機號碼:"+ mobile);
        System.out.println("驗證碼:"+ checkcode);

        smsUtil.sendSms(mobile, template_code, sing_name, "{\"code\":\"" + checkcode + "\"}");
    }
}


相關問題總結:

1秃诵、項目中哪部分業(yè)務用到消息隊列

用戶注冊發(fā)送短信驗證碼

2续搀、項目中使用哪種消息隊列?

rabbitMQ

3菠净、RabbitMQ 有哪幾種發(fā)送模式 ?

直接模式 禁舷、分列模式 、 主題模式毅往、 headers

4牵咙、項目中如何發(fā)送短信

阿里云通信(阿里大于)

?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市攀唯,隨后出現的幾起案子洁桌,更是在濱河造成了極大的恐慌,老刑警劉巖侯嘀,帶你破解...
    沈念sama閱讀 217,542評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件另凌,死亡現場離奇詭異谱轨,居然都是意外死亡,警方通過查閱死者的電腦和手機吠谢,發(fā)現死者居然都...
    沈念sama閱讀 92,822評論 3 394
  • 文/潘曉璐 我一進店門土童,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人工坊,你說我怎么就攤上這事献汗。” “怎么了王污?”我有些...
    開封第一講書人閱讀 163,912評論 0 354
  • 文/不壞的土叔 我叫張陵罢吃,是天一觀的道長。 經常有香客問我玉掸,道長刃麸,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,449評論 1 293
  • 正文 為了忘掉前任司浪,我火速辦了婚禮泊业,結果婚禮上,老公的妹妹穿的比我還像新娘啊易。我一直安慰自己吁伺,他們只是感情好,可當我...
    茶點故事閱讀 67,500評論 6 392
  • 文/花漫 我一把揭開白布租谈。 她就那樣靜靜地躺著篮奄,像睡著了一般。 火紅的嫁衣襯著肌膚如雪割去。 梳的紋絲不亂的頭發(fā)上窟却,一...
    開封第一講書人閱讀 51,370評論 1 302
  • 那天,我揣著相機與錄音呻逆,去河邊找鬼夸赫。 笑死,一個胖子當著我的面吹牛咖城,可吹牛的內容都是我干的茬腿。 我是一名探鬼主播,決...
    沈念sama閱讀 40,193評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼宜雀,長吁一口氣:“原來是場噩夢啊……” “哼切平!你這毒婦竟也來了?” 一聲冷哼從身側響起辐董,我...
    開封第一講書人閱讀 39,074評論 0 276
  • 序言:老撾萬榮一對情侶失蹤悴品,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發(fā)現了一具尸體苔严,經...
    沈念sama閱讀 45,505評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡菇存,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,722評論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了邦蜜。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,841評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡亥至,死狀恐怖悼沈,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情姐扮,我是刑警寧澤絮供,帶...
    沈念sama閱讀 35,569評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站茶敏,受9級特大地震影響壤靶,放射性物質發(fā)生泄漏。R本人自食惡果不足惜惊搏,卻給世界環(huán)境...
    茶點故事閱讀 41,168評論 3 328
  • 文/蒙蒙 一贮乳、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧恬惯,春花似錦向拆、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,783評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至碗暗,卻和暖如春颈将,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背言疗。 一陣腳步聲響...
    開封第一講書人閱讀 32,918評論 1 269
  • 我被黑心中介騙來泰國打工晴圾, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人洲守。 一個月前我還...
    沈念sama閱讀 47,962評論 2 370
  • 正文 我出身青樓疑务,卻偏偏與公主長得像,于是被迫代替她去往敵國和親梗醇。 傳聞我的和親對象是個殘疾皇子知允,可洞房花燭夜當晚...
    茶點故事閱讀 44,781評論 2 354

推薦閱讀更多精彩內容