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

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;
}

猜你喜欢

转载自www.cnblogs.com/zmj-learn/p/11425552.html