Java實(shí)現(xiàn)發(fā)送短信驗(yàn)證碼+redis限制發(fā)送的次數(shù)功能
java實(shí)現(xiàn)短信驗(yàn)證碼發(fā)送,由于我們使用第三方平臺(tái)進(jìn)行驗(yàn)證碼的發(fā)送,所以首先,我們要在一個(gè)平臺(tái)進(jìn)行注冊(cè)。這樣的平臺(tái)有很多,有的平臺(tái)在新建賬號(hào)的時(shí)候會(huì)附帶贈(zèng)幾條免費(fèi)短信。這里我僅做測(cè)試使用(具體哪個(gè)平臺(tái)見參考三,很簡(jiǎn)單,注冊(cè)賬號(hào)就行,記得添加短信簽名)。
另外,在實(shí)際項(xiàng)目中,如果有人惡意攻擊,不停的發(fā)送短信驗(yàn)證碼,就會(huì)造成很大的損失。故對(duì)發(fā)送次數(shù)做一定的限制就非常必要,這里我們限制一個(gè)手機(jī)號(hào)一天可以發(fā)多少短信和短信平臺(tái)無關(guān)。
這里采用的是存redis來實(shí)現(xiàn)這一個(gè)功能。就是每次調(diào)用發(fā)送驗(yàn)證碼這個(gè)接口都會(huì)判斷手機(jī)號(hào)碼是否在redis中存為key了。如果沒有則創(chuàng)建一個(gè)key為手機(jī)號(hào)碼value是1.因?yàn)閞edis中不支持?jǐn)?shù)字所以將其變?yōu)榱藄tring類型。如果redis中已經(jīng)有這個(gè)key了則將此key的值取出來加1再存進(jìn)redis中。
代碼實(shí)現(xiàn):
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.lmc</groupId>
<artifactId>springboot-sendsms</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-sendsms</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<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>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>RespBean.java
package com.lmc.bean;
public class RespBean {
private Integer status;
private String msg;
private Object obj;
public static RespBean build() {
return new RespBean();
}
public static RespBean ok(String msg) {
return new RespBean(200, msg, null);
}
public static RespBean ok(String msg, Object obj) {
return new RespBean(200, msg, obj);
}
public static RespBean error(String msg) {
return new RespBean(500, msg, null);
}
public static RespBean error(String msg, Object obj) {
return new RespBean(500, msg, obj);
}
private RespBean() {
}
private RespBean(Integer status, String msg, Object obj) {
this.status = status;
this.msg = msg;
this.obj = obj;
}
public Integer getStatus() {
return status;
}
public RespBean setStatus(Integer status) {
this.status = status;
return this;
}
public String getMsg() {
return msg;
}
public RespBean setMsg(String msg) {
this.msg = msg;
return this;
}
public Object getObj() {
return obj;
}
public RespBean setObj(Object obj) {
this.obj = obj;
return this;
}
}RedisConfig.java
package com.lmc.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import java.net.UnknownHostException;
@Configuration
public class RedisConfig {
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(jackson2JsonRedisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashKeySerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
@ConditionalOnMissingBean(StringRedisTemplate.class)
public StringRedisTemplate stringRedisTemplate(
StringRedisTemplate template = new StringRedisTemplate();
}SMSController.java
package com.lmc.controller;
import com.lmc.bean.RespBean;
import com.lmc.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* @description:
* @Author: lmc
* @date: 2021/12/26 10:21
*/
@RestController
public class SMSController {
@Autowired
StringRedisTemplate stringRedisTemplate;
@RequestMapping("/send")
public RespBean sendSMS() {
String Uid = "xxxxxxxx";
String Key = "xxxxxxxxxxxxxxx";
String smsMob = "xxxxxxxxx";
String sendSMSCount = "sendSMSCount:" + smsMob;
if ("2".equals(stringRedisTemplate.opsForValue().get(sendSMSCount))) {
return RespBean.error("今天已達(dá)到發(fā)送短信驗(yàn)證碼上限,請(qǐng)明天再試");
}
//短信內(nèi)容
String smsText = "歡迎使用xx系統(tǒng),驗(yàn)證碼:8888";
Map maps = new HashMap();
maps.put("Uid", Uid);
maps.put("Key", Key);
maps.put("smsMob", smsMob);
maps.put("smsText", smsText);
String result = HttpClientUtils.sendHttpPost("http://utf8.sms.webchinese.cn", maps);
int i = Integer.parseInt(result);
if (i > 0) {
if (stringRedisTemplate.opsForValue().get(sendSMSCount) == null) {
stringRedisTemplate.opsForValue().set(sendSMSCount, "1", getEndTime(), TimeUnit.MILLISECONDS);
} else {
String value = stringRedisTemplate.opsForValue().get(sendSMSCount);
int times = Integer.parseInt(value) + 1;
String timesStr = String.valueOf(times);
stringRedisTemplate.opsForValue().set(sendSMSCount, timesStr, getEndTime(), TimeUnit.MILLISECONDS);
}
return RespBean.ok("發(fā)送成功");
return RespBean.ok("發(fā)送失敗");
}
//獲取當(dāng)前時(shí)間到今天結(jié)束時(shí)間所剩余的毫秒數(shù):
public static long getEndTime() {
//獲取當(dāng)前時(shí)間的毫秒數(shù)
long time = new java.util.Date().getTime();
//獲取到今天結(jié)束的毫秒數(shù)
Calendar todayEnd = Calendar.getInstance();
todayEnd.set(Calendar.HOUR_OF_DAY, 23); // Calendar.HOUR 12小時(shí)制。HOUR_OF_DAY 24小時(shí)制
todayEnd.set(Calendar.MINUTE, 59);
todayEnd.set(Calendar.SECOND, 59);
todayEnd.set(Calendar.MILLISECOND, 999);
long endTime = todayEnd.getTimeInMillis();
//這里endTime-time獲取的是到23:59:59:999的毫秒數(shù)。再加1才是到24點(diǎn)整的毫秒數(shù)
return endTime-time+1;
}HttpClientUtils.java(HttpClient工具類,可以復(fù)用)
package com.lmc.utils;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpClientUtils {
private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
// 鏈接相關(guān)參數(shù)
private static int socketTimeout = 15000;
private static int connectTimeout = 15000;
private static int connectionRequestTimeout = 15000;
private static RequestConfig requestConfig = null;
// 連接池相關(guān)參數(shù)
private static int connMgrMaxTotal = 100;
private static int connMgrMaxPerRoute = 50;
private static PoolingHttpClientConnectionManager connMgr = null;
static {
requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout).build();
connMgr = new PoolingHttpClientConnectionManager();
connMgr.setDefaultMaxPerRoute(connMgrMaxPerRoute);
connMgr.setMaxTotal(connMgrMaxTotal);
}
private static String doHttp(HttpRequestBase httpRequestBase) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String responseContent = null;
try {
// 創(chuàng)建默認(rèn)的httpClient實(shí)例.
String scheme = httpRequestBase.getURI().getScheme();
if (scheme.equalsIgnoreCase("https")) {
PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpRequestBase.getURI().toString()));
DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).setConnectionManager(connMgr).build();
//httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
} else if (scheme.equalsIgnoreCase("http")) {
httpClient = HttpClients.custom().setConnectionManager(connMgr).build();
//httpClient = HttpClients.createDefault();
} else {
throw new IllegalArgumentException("url的scheme錯(cuò)誤,必須是http或者h(yuǎn)ttps! ");
}
httpRequestBase.setConfig(requestConfig);
// 執(zhí)行請(qǐng)求
response = httpClient.execute(httpRequestBase);
// 如果這里有必要獲取的是其他資料都可以在這里進(jìn)行邏輯處理
responseContent = EntityUtils.toString(response.getEntity(), "UTF-8");
return responseContent;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 關(guān)閉連接,釋放資源
if (response != null) {
// EntityUtils.consume(response.getEntity());
response.close();
}
// 這里不能關(guān)閉httpClient,這個(gè)會(huì)關(guān)鏈接池
//if (httpClient != null) {
// httpClient.close();
//}
} catch (IOException e) {
e.printStackTrace();
}
return responseContent;
/**
* sendHttpGet(url)
* @param url
* @return
*/
public static String sendHttpGet(String url) {
return doHttp(new HttpGet(url));
* sendHttpGet()
* @param param key1=value1&key2=value2&key3=value3
public static String sendHttpGet(String url, String param) {
// 創(chuàng)建httpGet
HttpGet httpGet = new HttpGet(url + '?' + param);
return doHttp(httpGet);
* sendHttpPost()
public static String sendHttpPost(String url, String param) {
// 創(chuàng)建httpPost
HttpPost httpPost = new HttpPost(url);
StringEntity stringEntity = new StringEntity(param, "UTF-8");
stringEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(stringEntity);
return doHttp(httpPost);
* sendHttpGet
* @param param 是個(gè)map<String, String>
public static String sendHttpGet(String url, Map<String, String> param) {
String paramStr = "";
for (String key : param.keySet()) {
String tmp = "";
tmp = "&" + key + "=" + param.get(key);
paramStr += tmp;
paramStr = paramStr.substring(1);
HttpGet httpGet = new HttpGet(url + '?' + paramStr);
return doHttp(httpGet);
* sendHttpPost
* @param param 是個(gè)map<String,String>
public static String sendHttpPost(String url, Map<String, String> param) {
// 創(chuàng)建參數(shù)隊(duì)列
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for (String key : param.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, param.get(key)));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
return doHttp(httpPost);
public static String sendHttpPostJson(String url, String json) {
// StringEntity stringEntity = new StringEntity(param, "UTF-8");
// stringEntity.setContentType("application/json");
// stringEntity.setContentEncoding("UTF-8");
StringEntity stringEntity = new StringEntity(json, ContentType.create("application/json", "UTF-8"));
public static void main(String[] args) {
String url = "http://api.crpay.com/payapi/gateway";
String param = "merchant_no=TOF00001&method=unified.trade.pay&version=1.0";
Map map = new HashMap<String, String>();
map.put("merchant_no", "TOF00001");
map.put("method", "unified.trade.pay");
map.put("version", "1.0");
// 這個(gè)工具是走的鏈接池,但是在關(guān)閉httpClient會(huì)關(guān)閉連接池的地方已經(jīng)注銷
//System.out.println(HttpClientUtils.sendHttpPost(url, map));
//System.out.println(HttpClientUtils.sendHttpPost(url, param));
//System.out.println(HttpClientUtils.sendHttpGet(url, map));
System.out.println(HttpClientUtils.sendHttpGet("https://www.baidu.com"));
System.out.println(HttpClientUtils.sendHttpGet("http://www.baidu.com/s?wd=aaa"));
Map map2 = new HashMap<String, String>();
map2.put("wd", "aaa");
System.out.println(HttpClientUtils.sendHttpGet("http://www.baidu.com/s",map2));
// doHttp是靜態(tài)私有方法,不能使用多次,會(huì)報(bào)Connection pool shut down
System.out.println(HttpClientUtils.doHttp(new HttpGet("http://www.baidu.com/s?wd=aaa")));
System.out.println(HttpClientUtils.doHttp(new HttpGet("https://www.baidu.com/")));
System.out.println(HttpClientUtils.sendHttpGet("https://www.cnblogs.com/hugo-zhangzhen/p/6858013.html"));
System.out.println(HttpClientUtils.sendHttpGet("https://www.cnblogs.com/hugo-zhangzhen/p/6739658.html"));
System.out.println(HttpClientUtils.sendHttpGet("https://www.cnblogs.com/hugo-zhangzhen/p/6737810.html"));
System.out.println(HttpClientUtils.sendHttpGet("http://blog.csdn.net/xiechengfa/article/details/42016153"));
}application.properties
# 配置redis spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password=123456
項(xiàng)目結(jié)果如下:

結(jié)果展示:
使用postman調(diào)用接口,超過2次后,顯示如下。

在具體項(xiàng)目中的流程一般如下:
①構(gòu)造手機(jī)驗(yàn)證碼,需要生成一個(gè)6位的隨機(jī)數(shù)字串;
②找短信平臺(tái)獲取使用接口向短信平臺(tái)發(fā)送手機(jī)號(hào)和驗(yàn)證碼,然后短信平臺(tái)再把驗(yàn)證碼發(fā)送到制定手機(jī)號(hào)上;
③將手機(jī)號(hào)驗(yàn)證碼、操作時(shí)間存入Session中,作為后面驗(yàn)證使用;
④接收用戶填寫的驗(yàn)證碼、手機(jī)號(hào)及其他注冊(cè)數(shù)據(jù);
⑤對(duì)比提交的驗(yàn)證碼與Session中的驗(yàn)證碼是否一致,同時(shí)判斷提交動(dòng)作是否在有效期內(nèi);
⑥驗(yàn)證碼正確且在有效期內(nèi),請(qǐng)求通過,處理相應(yīng)的業(yè)務(wù)。
參考:
接收短信驗(yàn)證碼條數(shù)限制(java發(fā)送短信驗(yàn)證碼限制) - 簡(jiǎn)書
Java如何實(shí)現(xiàn)短信驗(yàn)證碼功能? - 知乎
Java 實(shí)現(xiàn)手機(jī)發(fā)送短信驗(yàn)證碼 - 胖頭陀春天 - 博客園
到此這篇關(guān)于Java實(shí)現(xiàn)發(fā)送短信驗(yàn)證碼+redis限制發(fā)送的次數(shù)的文章就介紹到這了,更多相關(guān)java短信驗(yàn)證碼限制發(fā)送次數(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring?Boot開發(fā)時(shí)Java對(duì)象和Json對(duì)象之間的轉(zhuǎn)換
在Spring?Boot開發(fā)中,我們經(jīng)常需要處理Java對(duì)象和Json對(duì)象之間的轉(zhuǎn)換,本文將介紹如何在Spring?Boot項(xiàng)目中實(shí)現(xiàn)Java對(duì)象和Json對(duì)象之間的轉(zhuǎn)換,感興趣的朋友跟隨小編一起看看吧2023-09-09
springboot集成gzip和zip數(shù)據(jù)壓縮傳輸(適用大數(shù)據(jù)信息傳輸)
?在大數(shù)據(jù)量的傳輸中,壓縮數(shù)據(jù)后進(jìn)行傳輸可以一定程度的解決速度問題,本文主要介紹了springboot集成gzip和zip數(shù)據(jù)壓縮傳輸,具有一定的參考價(jià)值,感興趣的可以了解一下2023-09-09
SpringMVC4+MyBatis+SQL Server2014實(shí)現(xiàn)數(shù)據(jù)庫(kù)讀寫分離
這篇文章主要介紹了SpringMVC4+MyBatis+SQL Server2014實(shí)現(xiàn)讀寫分離,需要的朋友可以參考下2017-04-04
JAVA 16位ID生成工具類含16位不重復(fù)的隨機(jī)數(shù)數(shù)字+大小寫
這篇文章主要介紹了JAVA 16位ID生成工具類含16位不重復(fù)的隨機(jī)數(shù)數(shù)字+大小寫,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02
Java list如何根據(jù)id獲取子節(jié)點(diǎn)
這篇文章主要介紹了Java list如何根據(jù)id獲取子節(jié)點(diǎn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03
Java中的動(dòng)態(tài)代理實(shí)現(xiàn)代碼實(shí)例
這篇文章主要介紹了Java中的動(dòng)態(tài)代理實(shí)現(xiàn)代碼實(shí)例,jdk動(dòng)態(tài)代理本質(zhì)上是使用被代理對(duì)象的類加載器,通過被代理類實(shí)現(xiàn)的接口在運(yùn)行時(shí)動(dòng)態(tài)構(gòu)造出代理類來增強(qiáng)原始類的功能的方法,需要的朋友可以參考下2023-12-12
淺談java中null是什么,以及使用中要注意的事項(xiàng)
下面小編就為大家?guī)硪黄獪\談java中null是什么,以及使用中要注意的事項(xiàng)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-09-09

