前言
網(wǎng)上關(guān)于實(shí)操性的文章普遍大部分都記錄不全,要么只記錄重點(diǎn)部分,對(duì)于剛學(xué)習(xí)的小伙伴來說看起來是比較困難的
所以,基于這一點(diǎn)。
該文章會(huì)詳細(xì)介紹使用SpringBoot整合阿里云短信服務(wù)的每一步過程,同時(shí)會(huì)將驗(yàn)證碼存放到Redis中并設(shè)置過期時(shí)間,盡量保證實(shí)戰(zhàn)的同時(shí)也讓沒做過的同學(xué)也能實(shí)現(xiàn)發(fā)短信的功能~
關(guān)于阿里云短信服務(wù)介紹就不多說了,我們只要知道他能夠幫我們實(shí)現(xiàn)短信發(fā)送就夠了,直接上步驟~
1、開通阿里云短信服務(wù)
1、去到阿里云官方網(wǎng)址:https://www.aliyun.com/ 選擇短信服務(wù)
2、點(diǎn)擊開通即可
3、開通好后這里是需要申請(qǐng):自己的模板和簽名的,但現(xiàn)在申請(qǐng)的話需要有自己的域名和網(wǎng)站,對(duì)于剛學(xué)習(xí)的同學(xué)來說這些肯定是沒有的,但好在阿里云也考慮到了這個(gè)問題,就給我們提供了一個(gè)專門測(cè)試的簽名和模板
4、找到測(cè)試的簽名和模板,開通短信服務(wù)成功之后,會(huì)進(jìn)入到該頁面,我們點(diǎn)擊快速學(xué)習(xí),再往下滑,找到調(diào)用API發(fā)短信。
找不到的小伙伴可以直接點(diǎn)擊這個(gè)鏈接:阿里云短信服務(wù)測(cè)試的簽名和模板地址
到了這里,阿里云短信服務(wù)基本就搞定了,接下來我們整合到項(xiàng)目中。(對(duì)了,記得充點(diǎn)錢在里面,不然發(fā)送不了哦,幾毛就夠了,一條短信0.045)
2、整合短信服務(wù)到項(xiàng)目中
1、創(chuàng)建一個(gè)SpringBoot項(xiàng)目
2、導(dǎo)入依賴(為了讓大家看的更清楚,我這里就寫完整依賴了)
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.3.3</version>
</dependency>
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- spring2.X集成redis所需common-pool2-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.6.0</version>
</dependency>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<!--swagger ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
注意:記得將SpringBoot版本修改為2.2.1.RELEASE(因?yàn)楦甙姹镜挠锌赡懿黄ヅ洌?
3、配合application.properties文件
# 服務(wù)端口
server.port=8100
#Redis配置 這里填寫的是裝了redis的ip地址,我的redis裝在虛擬機(jī)中
spring.redis.host=192.168.1.8
spring.redis.port=6379
spring.redis.database= 0
spring.redis.timeout=1800000
spring.redis.lettuce.pool.max-active=20
spring.redis.lettuce.pool.max-wait=-1
#最大阻塞等待時(shí)間(負(fù)數(shù)表示沒限制)
spring.redis.lettuce.pool.max-idle=5
spring.redis.lettuce.pool.min-idle=0
#最小空閑
4、在啟動(dòng)類上加上對(duì)應(yīng)注解
@EnableSwagger2
@ComponentScan({"com.gx"})
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//取消數(shù)據(jù)源自動(dòng)配置
public class BootMsmApplication {
public static void main(String[] args) {
SpringApplication.run(BootMsmApplication.class, args);
}
}
5、創(chuàng)建service,編寫業(yè)務(wù)
(1)接口
/**
* @author Eric
* @create 2022-05-22 15:08
*/
public interface MsmService {
//發(fā)送驗(yàn)證碼
boolean send(Map<String, Object> param, String phone);
}
(2)實(shí)現(xiàn)類
package com.gx.bootmsm.service;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.Map;
/**
* @author Eric
* @create 2022-05-22 15:09
*/
@Service
public class MsmServiceImpl implements MsmService{
/**
* 發(fā)送驗(yàn)證碼
* @param param 驗(yàn)證碼
* @param phone 手機(jī)號(hào)
* @return
*/
@Override
public boolean send(Map<String, Object> param, String phone) {
if(StringUtils.isEmpty(phone)) return false;
//default 地域節(jié)點(diǎn),默認(rèn)就好 后面是 阿里云的 id和秘鑰(這里記得去阿里云復(fù)制自己的id和秘鑰哦)
DefaultProfile profile = DefaultProfile.getProfile("default", "Q2AtKVxX1N3tOh3AWHHzXyx", "ZgmmX3vSlMF9GnxliXZrLxoD7053Hx");
IAcsClient client = new DefaultAcsClient(profile);
//這里不能修改
CommonRequest request = new CommonRequest();
//request.setProtocol(ProtocolType.HTTPS);
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
request.putQueryParameter("PhoneNumbers", phone); //手機(jī)號(hào)
request.putQueryParameter("SignName", "阿里云短信測(cè)試"); //申請(qǐng)阿里云 簽名名稱(暫時(shí)用阿里云測(cè)試的,自己還不能注冊(cè)簽名)
request.putQueryParameter("TemplateCode", "SMS_154950909"); //申請(qǐng)阿里云 模板code(用的也是阿里云測(cè)試的)
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
return response.getHttpResponse().isSuccess();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
6、創(chuàng)建一個(gè)生成隨機(jī)驗(yàn)證碼的工具類:RandomUtil
package com.gx.bootmsm.utils;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
/**
* 獲取隨機(jī)數(shù)
*
* @author qianyi
*
*/
public class RandomUtil {
private static final Random random = new Random();
private static final DecimalFormat fourdf = new DecimalFormat("0000");
private static final DecimalFormat sixdf = new DecimalFormat("000000");
public static String getFourBitRandom() {
return fourdf.format(random.nextInt(10000));
}
public static String getSixBitRandom() {
return sixdf.format(random.nextInt(1000000));
}
/**
* 給定數(shù)組,抽取n個(gè)數(shù)據(jù)
* @param list
* @param n
* @return
*/
public static ArrayList getRandom(List list, int n) {
Random random = new Random();
HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
// 生成隨機(jī)數(shù)字并存入HashMap
for (int i = 0; i < list.size(); i++) {
int number = random.nextInt(100) + 1;
hashMap.put(number, i);
}
// 從HashMap導(dǎo)入數(shù)組
Object[] robjs = hashMap.values().toArray();
ArrayList r = new ArrayList();
// 遍歷數(shù)組并打印數(shù)據(jù)
for (int i = 0; i < n; i++) {
r.add(list.get((int) robjs[i]));
System.out.print(list.get((int) robjs[i]) + "\t");
}
System.out.print("\n");
return r;
}
}
7、創(chuàng)建controller
package com.gx.bootmsm.controller;
import com.gx.bootmsm.service.MsmService;
import com.gx.bootmsm.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* @author Eric
* @create 2022-05-22 15:12
*/
@Api(tags = "阿里云短信服務(wù)")
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {
@Autowired
private MsmService msmService;
@Autowired
private RedisTemplate<String, String> redisTemplate; //注入redis
//發(fā)送短信驗(yàn)證碼
@ApiOperation(value = "發(fā)送短信驗(yàn)證碼")
@GetMapping(value = "/send/{phone}")
public Boolean code(@PathVariable String phone) {
//1、從redis中獲取驗(yàn)證碼,如果獲取到就直接返回
String code = redisTemplate.opsForValue().get(phone);
if(!StringUtils.isEmpty(code)) return false;
//2、如果獲取不到,就進(jìn)行阿里云發(fā)送
code = RandomUtil.getFourBitRandom();//生成驗(yàn)證碼的隨機(jī)值
Map<String,Object> param = new HashMap<>();
param.put("code", code);
//調(diào)用方法
boolean isSend = msmService.send(param,phone);
if(isSend) {
//往redis中設(shè)置數(shù)據(jù):key、value、過期值、過期時(shí)間單位 MINUTES代表分鐘
redisTemplate.opsForValue().set(phone, code,5, TimeUnit.MINUTES);
return true;
} else {
return false;
}
}
}
3、測(cè)試
1、啟動(dòng)項(xiàng)目
2、訪問swagger地址:http://localhost:8100/swagger-ui.html
3、輸入手機(jī)號(hào),點(diǎn)擊發(fā)送
返回結(jié)果為true,說明發(fā)送成功
這是手機(jī)收到的短信
因?yàn)槲覀冇玫氖前⒗镌频哪0?,所以模板顯示我們也就不能自定義啦~
然后我們也用到了redis,設(shè)置了驗(yàn)證碼的過期時(shí)間,我們可以去到redis中查看是否有值
可以看到已經(jīng)存放進(jìn)來了~文章來源:http://www.zghlxwxcb.cn/news/detail-414180.html
總結(jié)
該文章應(yīng)該是每一步都有記錄,也是幫自己回憶一下這個(gè)過程,當(dāng)然,如果對(duì)你也有幫助,那也是我的榮幸~ ,如果在過程中有遇到問題,可在下方留言,作者看到會(huì)在第一時(shí)間回復(fù)。文章來源地址http://www.zghlxwxcb.cn/news/detail-414180.html
到了這里,關(guān)于SpringBoot整合阿里云短信服務(wù)詳細(xì)過程(保證初學(xué)者也能實(shí)現(xiàn))的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!