springboot网站开发-使用redis作为定时器控制手机号每日注册次数!为了避免,某些手机号,频繁的申请注册,开启了redis数据库配置的定时器模式。下面是设计代码的案例展示。
1:
package com.blog.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.concurrent.TimeUnit;
public class VerificationPhone {
private static Logger alogger = LoggerFactory.getLogger("xx_xunwu");
@Resource
private RedisTemplate<String, Object> redisTemplate;
/**
* 每个手机号,每天仅有2次注册的机会
* @param phone
* @return
*/
public boolean VerificationPhoneForRegisterByPhone(String phone){
try {
// 2.使用phone作为key,今天的日期作为prefix
String key = "rate:limit:register:" + phone + ":";
String date = LocalDate.now().toString();
key += date;
System.out.println("keyinfo:" + key);
// 3.检查用户今天的请求次数
ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
//查询redis内是否已经存在当前username日期组合的信息
Integer count = (Integer) opsForValue.get(key);
// 4.如果是第一次请求或者超过24小时,重置计数
if (count == null) {
count = 0;
System.out.println("您今天是第一次申请注册手机号,可以正常使用");
// 更新请求计数
count++;
opsForValue.set(key, count, 24, TimeUnit.HOURS); // 设置键的过期时间为24小时
//
} else if (count != null && count <2) {
// 更新请求计数
count++;
opsForValue.set(key, count, 24, TimeUnit.HOURS); // 设置键的过期时间为24小时
//
}else if(count !=null && count >=2){
System.out.println("您今天已经申请2次了,次数用完了,请明天再来尝试");
return false;
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
alogger.info("验证手机号是否还有注册次数时遇到故障:"+e.getMessage());
}
return true;
}
}
经过这样设置,我们可以限制用户的手机号,每天24小时之内,仅有2次申请注册的机会,你可以根据个人的业务需求,自己修改限制的次数。我这里是设置了2.
24小时之后,这条数据库记录信息会自动被清理干净,客户就可以再次申请了。