java实现发送短信验证码 redis限制发送的次数功能-亚博电竞手机版

java实现短信验证码发送,由于我们使用第三方平台进行验证码的发送,所以首先,我们要在一个平台进行注册。这样的平台有很多,有的平台在新建账号的时候会附带赠几条免费短信。这里我仅做测试使用(具体哪个平台见参考三,很简单,注册账号就行,记得添加短信签名)。

另外,在实际项目中,如果有人恶意攻击,不停的发送短信验证码,就会造成很大的损失。故对发送次数做一定的限制就非常必要,这里我们限制一个手机号一天可以发多少短信和短信平台无关。

这里采用的是存redis来实现这一个功能。就是每次调用发送验证码这个接口都会判断手机号码是否在redis中存为key了。如果没有则创建一个key为手机号码value是1.因为redis中不支持数字所以将其变为了string类型。如果redis中已经有这个key了则将此key的值取出来加1再存进redis中。

代码实现:

pom.xml

4.0.0 org.springframework.boot spring-boot-starter-parent 2.6.2 com.lmc springboot-sendsms 0.0.1-snapshot springboot-sendsms demo project for spring boot 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.apache.httpcomponents httpclient org.springframework.boot spring-boot-starter-data-redis org.springframework.boot spring-boot-maven-plugin

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 redistemplate( redisconnectionfactory redisconnectionfactory) throws unknownhostexception { jackson2jsonredisserializer

网站地图