redis判断1分钟统一手机号发送短信次数不超过5次

本文介绍了一种基于Redis的短信重发服务限频机制,通过存储和检查短信发送记录,防止短时间内对同一手机号码的频繁短信发送,确保了系统的稳定性和用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public SmsMessageRes sendSMS(String mobile, String message,String type,String companyCode) {
logger.info("调用发送短信服务:开始...................");
JSONObject object = new JSONObject();
object.put("mobile", mobile);
object.put("message", message);
object.put("type", type);
object.put("companyCode", companyCode);
Object send = null;
int index=0;
String Countvalue ="";
long currentTime=System.currentTimeMillis();
long currentfiveTime = currentTime-60000;//一分钟前时间戳
try {
String limitCountKey = mobile+"_limitCount";//每个手机号码就代表是一个用户
Object limitCountvalue = CacheManager.getInstance().getCache(limitCountKey);//查询redis中的缓存
if(limitCountvalue==null){//第一次发短信
send = this.send(object.toString(), "SMS", "SMS Server");
CacheManager.getInstance().putCache(limitCountKey, currentTime+""); //存储redis缓存,也可使用list类型缓存
}else{
String limitCountvalues=limitCountvalue+"";
String[] arr = limitCountvalues.split(",");
for(int i=0;i<arr.length;i++){
if(Long.parseLong(arr[i])>currentfiveTime){//超出时间的缓存去除掉
index++;
if("".equals(Countvalue)){
Countvalue = arr[i];
}else{
Countvalue += "," + arr[i];
}

}
}
if("".equals(Countvalue)){
Countvalue = currentTime+"";
}else{
Countvalue += "," + currentTime;
}

if(index>4){//1分钟内超过5次不发送短信
send = null;
logger.info(mobile+" 发送消息太频繁:失败");
}else{
send = this.send(object.toString(), "SMS", "SMS Server"); //调用短信服务
}
CacheManager.getInstance().putCache(limitCountKey, Countvalue); //redis 存储
}
} catch (MessagingException e) {
logger.info(mobile+" 发送消息:失败", e);
}
SmsMessageRes res = new SmsMessageRes();
res.setMobile(mobile);
res.setMessage(message);
if(send != null){
JSONObject rev = JSONObject.fromObject(send);
String object2 = (String) rev.get("status");
if(StringUtils.equalsIgnoreCase(object2, "true")){
res.setStatus(true);
}
}
logger.info("调用发送短信服务:结束...................");
return res;
}

转载于:https://www.cnblogs.com/zmj-learn/p/11425552.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值