限制每个用户访问接口的次数(Java)

本文介绍了一种使用缓存管理器来限制同一手机号码在一分钟内发送短信次数的方法,并通过计数确保不会超过三次,以此避免短信滥发。

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

Java code
?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
private  boolean  checkSendMobile2(String mobile){
         int  limitCount =  0 ;
         Object obj = UserCacheManager.getValue( "SEND_SMS_TYPE" ,
                 mobile);
         String limitCountKey = mobile+ "_limitCount" ; //每个手机号码就代表是一个用户
         if (UserCacheManager.getValue( "SEND_SMS_LIMIT_COUNT" , limitCountKey)== null ){
             limitCount =  1 ; // 记录第一次
         } else {
             limitCount = ( int ) UserCacheManager.getValue( "SEND_SMS_LIMIT_COUNT" , limitCountKey);
         }
         
         if  (obj  instanceof  Long) {
             long  time = (Long) obj;
             if (System.currentTimeMillis() - time <  1  60  1000 ){
                 //如果是在一分钟之内 则判断访问次数
                 limitCount++;
                 UserCacheManager.put( "SEND_SMS_LIMIT_COUNT" , limitCountKey, limitCount);
                 if (limitCount> 3 ){
                     //如果大于三次 则调用次数过多
                     return  true ;
                 } else {
                     return  false ;
                 }
             } else {
                 //超过一分钟
                 limitCount =  1 ; //次数重新赋值1
                 //同时保存用户访问次数和时间
                 UserCacheManager.put( "SEND_SMS_TYPE" , mobile,  new  Date().getTime());
                 UserCacheManager.put( "SEND_SMS_LIMIT_COUNT" , limitCountKey, limitCount);
                 return  false ;
             }
         else  {
             //没有保存用户访问时间, 则说明第一次访问
             UserCacheManager.put( "SEND_SMS_TYPE" , mobile,  new  Date().getTime());
             UserCacheManager.put( "SEND_SMS_LIMIT_COUNT" , limitCountKey, limitCount);
             return  false ;
         }
     }

map<用户,List<时间(long)>>
比如你吧用户信息也传到这个方法里面去,map.get就能找到你最近访问的时间记录了,几点几分第一次,几点几分第二次,
还是按照时间先后顺序排列,都已经这样了。
for(List<时间(long)>){
if(list.get(i)-当前时间<三分钟){
    ++n;
}
}
if(n>3){
throw ;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值