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ā)送短信
阿里云通信(阿里大于)