1 28 29 package com.caucho.filters; 30 31 import com.caucho.log.Log; 32 import com.caucho.util.IntMap; 33 import com.caucho.util.L10N; 34 35 import javax.servlet.Filter ; 36 import javax.servlet.FilterChain ; 37 import javax.servlet.FilterConfig ; 38 import javax.servlet.ServletException ; 39 import javax.servlet.ServletRequest ; 40 import javax.servlet.ServletResponse ; 41 import javax.servlet.http.HttpServletResponse ; 42 import java.io.IOException ; 43 import java.util.logging.Logger ; 44 45 48 public class ThrottleFilter implements Filter { 49 private static final L10N L = new L10N(ThrottleFilter.class); 50 private static final Logger log = Log.open(ThrottleFilter.class); 51 52 private IntMap _throttleCache = new IntMap(); 53 54 private int _maxConcurrentRequests = 2; 55 56 59 public void setMaxConcurrentRequests(int max) 60 { 61 _maxConcurrentRequests = max; 62 } 63 64 public void init(FilterConfig config) 65 throws ServletException 66 { 67 } 68 69 public void doFilter(ServletRequest request, ServletResponse response, 70 FilterChain nextFilter) 71 throws ServletException , IOException 72 { 73 String ip = request.getRemoteAddr(); 74 boolean isOverflow; 75 76 synchronized (this) { 77 int count = _throttleCache.get(ip); 78 79 if (count <= 0) 80 count = 0; 81 82 if (count < _maxConcurrentRequests) { 83 isOverflow = false; 84 _throttleCache.put(ip, count + 1); 85 } 86 else 87 isOverflow = true; 88 } 89 90 if (isOverflow) { 91 log.info(L.l("'{0}' has too many concurrent requests -- throttling.", 92 ip)); 93 94 if (response instanceof HttpServletResponse ) 95 ((HttpServletResponse ) response).sendError(503); 96 return; 97 } 98 99 try { 100 nextFilter.doFilter(request, response); 101 } finally { 102 synchronized (this) { 103 int count = _throttleCache.get(ip); 104 105 if (count <= 1) 106 _throttleCache.remove(ip); 107 else 108 _throttleCache.put(ip, count - 1); 109 } 110 } 111 } 112 113 116 public void destroy() 117 { 118 } 119 } 120 | Popular Tags |