假设需求是这样,一个手机号每日可以发送三次短信验证,如果三次次数使用完后,就等到24:00后才可以再发
分析:
将手机号加上```:code```作为key存入redis中,如 (这个作为key)13456789090:code (随机生成的验证码作为value,并设置过期时间)123456
将手机号加上```:count```作为key存入redis中,如 (key)13456789090:count (发送次数作为value,没发送一次累加一次) 1
(ps: 可以按照自己的喜好设置后缀,":code"后缀为表示存放验证码,":count"后缀表示发送次数)
demo架构:maven+spring+springmvc+redis
项目使用web2.5模型
项目地址
GitHub - MovingBricksG/JedisDemo: jedis模拟短信验证demo
主要代码
@RestController
@RequestMapping("/send")
public class SendCodeController {
@Autowired
JedisCacheService jedisCache;
/**
* 通过手机号发送验证码
* @param number
* @return
*/
@RequestMapping("/sendCode")
public Map<String, Object> sendCode(String number) {
String key = number + CodeConfig.COUNT_SUFFIX;
// 首先判断key是否存在
if (jedisCache.existKey(key)) {
String c = jedisCache.get(key);
Integer count = Integer.valueOf(c);
count = count + 1;
// 当前次数加一后重新set
Integer expireTime = CodeConfig.SECONDS_PER_DAY - CommonUtils.getCurTime();
jedisCache.setWithExpire(key, String.valueOf(count), expireTime);
} else {
// 若不存在,则直接将count设为1并存入到redis中
jedisCache.set(number + CodeConfig.COUNT_SUFFIX, "1");
}
// 获取验证码,写入到redis并返回给前端
String code = CommonUtils.getCode(CodeConfig.CODE_LEN);
jedisCache.setWithExpire(number + CodeConfig.PHONE_SUFFIX, code, CodeConfig.CODE_TIMEOUT);
return CommonUtils.resultMap(1, "", "success", code);
}
// 用来测试redis是否连接,可自行在redis中设置key为k1的键值对
@RequestMapping("/test")
public Map<String, Object> testRedis() {
System.out.println(jedisCache.get("k1"));
return CommonUtils.resultMap(1, "", "success", jedisCache.get("k1"));
}
}
@RestController
@RequestMapping("/check")
public class CheckCodeController {
@Autowired
JedisCacheService jedisCache;
/**
* 校验是否可以发送验证码
* @param number
* @return
*/
@RequestMapping("/canSend")
public Map<String, Object> canSend(String number) {
if (!StringUtils.isEmpty(number)) { // 后端二次校验手机号是否为空
String countKey = number + CodeConfig.COUNT_SUFFIX;
if (jedisCache.existKey(countKey)) { // 判断是否存在key
String count = jedisCache.get(countKey);
if (Integer.valueOf(count) == CodeConfig.COUNT_TIMES_1DAY) {
return CommonUtils.resultMap(0, "", "今日已达到上限验证次数,请明天重试", "");
}
return CommonUtils.resultMap(1, "", "success", "");
}
// 若不存在表示可以发送
return CommonUtils.resultMap(1, "", "success", "");
}
return CommonUtils.resultMap(0, "", "手机号填写为空", "");
}
/**
* 校验手机号获取到的验证码
* @param number
* @param code
* @return
*/
@RequestMapping("/checkCode")
public Map<String, Object> checkCode(String number, String code) { // 先不做number和code的二次校验了
String phoneKey = number + CodeConfig.PHONE_SUFFIX;
// 首先校验验证码是否已经过期
if (jedisCache.existKey(phoneKey)) {
String value = jedisCache.get(phoneKey);
if (value.equals(code)) {
// 验证成功,就将redis中的验证码删掉
jedisCache.del(phoneKey);
return CommonUtils.resultMap(1, "", "验证成功", "");
}
return CommonUtils.resultMap(0, "", "验证码错误", "");
}
return CommonUtils.resultMap(0, "", "验证码错误或者已过期", "");
}
}
@Service
public class JedisCacheService {
@Autowired //自动注入redis连接池
private JedisPool jedisPool;
public void set(String key, String value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.set(key, value);
} catch (Exception e) {
e.printStackTrace();
} finally {
this.close(jedis);
}
}
public void setWithExpire(String key, String value, Integer times) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.set(key, value);
jedis.expire(key, times);
} catch (Exception e) {
e.printStackTrace();
} finally {
this.close(jedis);
}
}
public boolean existKey(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.exists(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
this.close(jedis);
}
return false;
}
public String getHash(String key, String field) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String hget = jedis.hget(key, field);
return hget;
} catch (Exception e) {
e.printStackTrace();
} finally {
this.close(jedis);
}
return null;
}
public void setHash(String key, Map<String, String> map) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.hmset(key, map);
} catch (Exception e) {
e.printStackTrace();
} finally {
this.close(jedis);
}
}
public void del(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.del(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
this.close(jedis);
}
}
public String get(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String s = jedis.get(key);
return s;
} catch (Exception e) {
e.printStackTrace();
} finally {
this.close(jedis);
}
return null;
}
public void close(Jedis jedis){
if (jedis != null) {
jedis.close();
if (jedis.isConnected()) {
try {
jedis.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
springmvc.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 组件扫描 -->
<context:component-scan base-package="com.gch"></context:component-scan>
<!-- 配置redis连接 -->
<bean class="redis.clients.jedis.JedisPool" id="jedisPool">
<constructor-arg name="host" value="192.168.1.100"></constructor-arg>
<constructor-arg name="port" value="6379"></constructor-arg>
</bean>
<!-- 配置静态资源处理 -->
<mvc:default-servlet-handler />
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>
<property name="features">
<array>
<value>WriteMapNullValue</value>
<value>WriteNullStringAsEmpty</value>
</array>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
</beans>
可能会出现的问题就是项目启动时会报错,因为没有将maven依赖部署到WEB-INF/lib内,此时 项目 -> 右键 -> BuildPath -> 滚轮往上滚找到Deployment Assembly
按照下面步骤操作:1.选择Deployment Assembly 2.点击 Add 3.选择Java Bulid Path Entries后下一步 4.选择Maven Dependencies点finish

image.png

step.png