WANG 5 years ago
parent
commit
6554e3a05e

+ 13 - 0
src/main/java/cn/com/qmth/examcloud/web/interceptor/ApiFlowLimitedInterceptor.java

@@ -11,6 +11,7 @@ import org.springframework.http.HttpStatus;
 import org.springframework.web.servlet.HandlerInterceptor;
 import org.springframework.web.servlet.HandlerInterceptor;
 
 
 import com.google.common.collect.Maps;
 import com.google.common.collect.Maps;
+import com.google.common.util.concurrent.RateLimiter;
 import com.googlecode.aviator.AviatorEvaluator;
 import com.googlecode.aviator.AviatorEvaluator;
 
 
 import cn.com.qmth.examcloud.commons.logging.ExamCloudLog;
 import cn.com.qmth.examcloud.commons.logging.ExamCloudLog;
@@ -37,10 +38,15 @@ public class ApiFlowLimitedInterceptor implements HandlerInterceptor {
 	private static final ExamCloudLog LOG = ExamCloudLogFactory
 	private static final ExamCloudLog LOG = ExamCloudLogFactory
 			.getLog(ApiFlowLimitedInterceptor.class);
 			.getLog(ApiFlowLimitedInterceptor.class);
 
 
+	private static final RateLimiter rateLimiter;
+
 	private static Properties props = new Properties();
 	private static Properties props = new Properties();
 
 
 	static {
 	static {
 
 
+		double permitsPerSecond = PropertyHolder.getInt("examcloud.api.permitsPerSecond", 10000);
+		rateLimiter = RateLimiter.create(permitsPerSecond);
+
 		new Thread(new Runnable() {
 		new Thread(new Runnable() {
 			@Override
 			@Override
 			public void run() {
 			public void run() {
@@ -73,6 +79,13 @@ public class ApiFlowLimitedInterceptor implements HandlerInterceptor {
 			return true;
 			return true;
 		}
 		}
 
 
+		boolean acquired = rateLimiter.tryAcquire();
+		if (!acquired) {
+			response.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value());
+			ServletUtil.returnJson(new StatusResponse("503", "limited"), response);
+			return false;
+		}
+
 		ApiInfo apiInfo = (ApiInfo) request
 		ApiInfo apiInfo = (ApiInfo) request
 				.getAttribute(HttpServletRequestAttribute.$_API_INFO.name());
 				.getAttribute(HttpServletRequestAttribute.$_API_INFO.name());