使用spring拦截器做频率限制

1. 注解类 Frequency

[java]  view plain  copy
  1. @Target ({ElementType.TYPE, ElementType.METHOD})      
  2. @Retention (RetentionPolicy.RUNTIME)      
  3. @Documented       
  4. @Component      
  5. public @interface Frequency {  
  6.   
  7.     String name() default "all";  
  8.     int time()  default 0;  
  9.     int limit()  default 0;  
  10. }  

2. 拦截对象封装 FrequencyStruct

[java]  view plain  copy
  1. public class FrequencyStruct {  
  2.   
  3.     String uniqueKey;  
  4.     long start;  
  5.     long end;  
  6.     int time;  
  7.     int limit;  
  8.     List<Long> accessPoints = new ArrayList<Long>();  
  9.       
  10.     public void reset(long timeMillis) {  
  11.           
  12.         start = end = timeMillis;  
  13.         accessPoints.clear();  
  14.         accessPoints.add(timeMillis);  
  15.     }  
  16.   
  17.     @Override  
  18.     public String toString() {  
  19.         return "FrequencyStruct [uniqueKey=" + uniqueKey + ", start=" + start  
  20.                 + ", end=" + end + ", time=" + time + ", limit=" + limit  
  21.                 + ", accessPoints=" + accessPoints + "]";  
  22.     }  
  23. }  


3. FrequencyHandlerInterceptor会拦截所有带Frequency注解的类或方法

如果是有负载情况下,会取x-forwarded-for头里的ip地址,经过负载的请求必须带x-forwarded-for头,记录用户ip。

频率限制使用本地内存做数据基站,初始化时会开辟MAX_BASE_STATION_SIZE长度的HashMap,MAX_BASE_STATION_SIZE得默认值是100000。

[java]  view plain  copy
  1. public class FrequencyHandlerInterceptor extends HandlerInterceptorAdapter {  
  2.       
  3.     private Logger logger = LoggerFactory.getLogger(FrequencyHandlerInterceptor.class);   
  4.     private static final int MAX_BASE_STATION_SIZE = 100000;  
  5.     private static Map<String, FrequencyStruct> BASE_STATION = new HashMap<String, FrequencyStruct>(MAX_BASE_STATION_SIZE);  
  6.     private static final float SCALE = 0.75F;  
  7.     private static final int MAX_CLEANUP_COUNT = 3;  
  8.     private static final int CLEANUP_INTERVAL = 1000;  
  9.     private Object syncRoot = new Object();  
  10.     private int cleanupCount = 0;  
  11.       
  12.     @Override  
  13.     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {  
  14.           
  15.         Frequency methodFrequency = ((HandlerMethod) handler).getMethodAnnotation(Frequency.class);  
  16.         Frequency classFrequency = ((HandlerMethod) handler).getBean().getClass().getAnnotation(Frequency.class);  
  17.           
  18.         boolean going = true;  
  19.         if(classFrequency != null) {  
  20.             going = handleFrequency(request, response, classFrequency);  
  21.         }  
  22.           
  23.         if(going && methodFrequency != null) {  
  24.             going = handleFrequency(request, response, methodFrequency);  
  25.         }  
  26.         return going;  
  27.     }  
  28.   
  29.     private boolean handleFrequency(HttpServletRequest request, HttpServletResponse response, Frequency frequency) {  
  30.           
  31.         boolean going = true;  
  32.         if(frequency == null) {  
  33.             return going;  
  34.         }  
  35.           
  36.         String name = frequency.name();  
  37.         int limit = frequency.limit();  
  38.         int time = frequency.time();  
  39.           
  40.         if(time == 0 || limit == 0) {  
  41.             going = false;  
  42.             response.setStatus(HttpServletResponse.SC_FORBIDDEN);  
  43.             return going;  
  44.         }  
  45.               
  46.         long currentTimeMilles = System.currentTimeMillis() / 1000;  
  47.           
  48.         String ip = getRemoteIp(request);  
  49.         String key = ip + "_" + name;  
  50.         FrequencyStruct frequencyStruct = BASE_STATION.get(key);  
  51.           
  52.         if(frequencyStruct == null) {  
  53.               
  54.             frequencyStruct = new FrequencyStruct();  
  55.             frequencyStruct.uniqueKey = name;  
  56.             frequencyStruct.start = frequencyStruct.end = currentTimeMilles;  
  57.             frequencyStruct.limit = limit;  
  58.             frequencyStruct.time = time;  
  59.             frequencyStruct.accessPoints.add(currentTimeMilles);  
  60.   
  61.             synchronized (syncRoot) {  
  62.                 BASE_STATION.put(key, frequencyStruct);  
  63.             }  
  64.             if(BASE_STATION.size() > MAX_BASE_STATION_SIZE * SCALE) {  
  65.                 cleanup(currentTimeMilles);  
  66.             }  
  67.         } else {  
  68.               
  69.             frequencyStruct.end = currentTimeMilles;  
  70.             frequencyStruct.accessPoints.add(currentTimeMilles);  
  71.         }  
  72.           
  73.         //时间是否有效  
  74.         if(frequencyStruct.end - frequencyStruct.start >= time) {  
  75.               
  76.             if(logger.isDebugEnabled()) {  
  77.                 logger.debug("frequency struct be out of date, struct will be reset., struct: {}", frequencyStruct.toString());  
  78.             }  
  79.             frequencyStruct.reset(currentTimeMilles);  
  80.         } else {  
  81.               
  82.             int count = frequencyStruct.accessPoints.size();  
  83.             if(count > limit) {  
  84.                 if(logger.isDebugEnabled()) {  
  85.                     logger.debug("key: {} too frequency. count: {}, limit: {}.", key, count, limit);  
  86.                 }  
  87.                 going = false;  
  88.                 response.setStatus(HttpServletResponse.SC_FORBIDDEN);  
  89.             }  
  90.         }  
  91.         return going;  
  92.     }  
  93.   
  94.     private void cleanup(long currentTimeMilles) {  
  95.           
  96.         synchronized (syncRoot) {  
  97.               
  98.             Iterator<String> it = BASE_STATION.keySet().iterator();  
  99.             while(it.hasNext()) {  
  100.                   
  101.                 String key = it.next();  
  102.                 FrequencyStruct struct = BASE_STATION.get(key);  
  103.                 if((currentTimeMilles - struct.end) > struct.time) {  
  104.                     it.remove();  
  105.                 }  
  106.             }  
  107.               
  108.             if((MAX_BASE_STATION_SIZE - BASE_STATION.size()) > CLEANUP_INTERVAL) {  
  109.                 cleanupCount = 0;  
  110.             } else {  
  111.                 cleanupCount++;  
  112.             }  
  113.               
  114.             if(cleanupCount > MAX_CLEANUP_COUNT ) {  
  115.                 randomCleanup(MAX_CLEANUP_COUNT);  
  116.             }  
  117.         }  
  118.     }  
  119.   
  120.     /** 
  121.      * 随机淘汰count个key 
  122.      *  
  123.      * @param maxCleanupCount 
  124.      */  
  125.     private void randomCleanup(int count) {  
  126.         //防止调用错误  
  127.         if(BASE_STATION.size() < MAX_BASE_STATION_SIZE * SCALE) {  
  128.             return;  
  129.         }  
  130.           
  131.         Iterator<String> it = BASE_STATION.keySet().iterator();  
  132.         Random random = new Random();  
  133.         int tempCount = 0;  
  134.           
  135.         while(it.hasNext()) {  
  136.             if(random.nextBoolean()) {  
  137.                 it.remove();  
  138.                 tempCount++;  
  139.                 if(tempCount >= count) {  
  140.                     break;  
  141.                 }  
  142.             }  
  143.         }  
  144.     }  
  145.       
  146.     private String getRemoteIp(HttpServletRequest request) {  
  147.   
  148.         String ip = request.getHeader("x-forwarded-for");  
  149.         if(StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {  
  150.             ip = request.getHeader("Proxy-Client-IP");  
  151.         }  
  152.   
  153.         if(StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {  
  154.             ip = request.getHeader("WL-Proxy-Client-IP");  
  155.         }  
  156.   
  157.         if(StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {  
  158.             ip = request.getRemoteAddr();  
  159.         }  
  160.   
  161.         return ip;  
  162.   
  163.     }  
  164. }  

4. 配置使用

[html]  view plain  copy
  1. <!-- 拦截器配置 -->  
  2.     <mvc:interceptors>    
  3.         <!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 -->   
  4.         <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />    
  5.         <!-- 如果不定义 mvc:mapping path 将拦截所有的URL请求 -->  
  6.         <bean class="xxx.annotation.FrequencyHandlerInterceptor"></bean>  
  7.     </mvc:interceptors>  

5. 可以使用在Controller或单独某个方法上。最好给每个name都定义单独的name,默认all的范围太广,使用方法如下:

[java]  view plain  copy
  1. @Controller  
  2. @RequestMapping("/demo")  
  3. @Frequency(name="demo", limit=3, time=1)  
  4. public class DemoController {  
  5.   
  6.     @RequestMapping(value = {"index"})  
  7.   
  8.      @Frequency(name="method", limit=3, time=1)  
  9.   
  10.      public void method()  
  11.   
  12. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值