From dc51e6bf7f20b2786bd16dc3e951ab8a299f4a34 Mon Sep 17 00:00:00 2001 From: Junjie <fallin.jie@qq.com> Date: 星期三, 09 八月 2023 09:32:12 +0800 Subject: [PATCH] 接口频率限制注解 --- src/main/java/com/zy/common/config/AdminInterceptor.java | 19 +++++++++++++++++-- 1 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/zy/common/config/AdminInterceptor.java b/src/main/java/com/zy/common/config/AdminInterceptor.java index 85d7e4a..2db00f8 100644 --- a/src/main/java/com/zy/common/config/AdminInterceptor.java +++ b/src/main/java/com/zy/common/config/AdminInterceptor.java @@ -4,8 +4,10 @@ import com.core.annotations.ManagerAuth; import com.core.common.BaseRes; import com.core.common.Cools; +import com.google.common.util.concurrent.RateLimiter; import com.zy.asrs.entity.ApiConfig; import com.zy.asrs.service.ApiConfigService; +import com.zy.common.model.annotations.RateLimit; import com.zy.common.utils.Http; import com.zy.system.entity.Permission; import com.zy.system.entity.RolePermission; @@ -14,6 +16,7 @@ import com.zy.system.service.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; import org.springframework.lang.Nullable; import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; @@ -23,6 +26,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.Method; +import java.util.concurrent.TimeUnit; /** * Created by vincent on 2019-06-13 @@ -45,12 +49,25 @@ @Autowired private ApiConfigService apiConfigService; + private final RateLimiter rateLimiter = RateLimiter.create(10);// 榛樿姣忕鏈�澶氬鐞� 10 涓姹� + @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { cors(response); if (handler instanceof org.springframework.web.servlet.resource.ResourceHttpRequestHandler) { return true; } + HandlerMethod handlerMethod = (HandlerMethod) handler; + Method method = handlerMethod.getMethod(); + if (method.isAnnotationPresent(RateLimit.class)){ + RateLimit annotation = method.getAnnotation(RateLimit.class); + rateLimiter.setRate(annotation.value()); + if (!rateLimiter.tryAcquire(annotation.value(), TimeUnit.SECONDS)) { + response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value()); + return false; + } + } + // super璐﹀彿 String token = request.getHeader("token"); if (token!=null) { @@ -70,8 +87,6 @@ } // 璺ㄥ煙璁剧疆 // response.setHeader("Access-Control-Allow-Origin", "*"); - HandlerMethod handlerMethod = (HandlerMethod) handler; - Method method = handlerMethod.getMethod(); if (method.isAnnotationPresent(ManagerAuth.class)){ ManagerAuth annotation = method.getAnnotation(ManagerAuth.class); if (annotation.value().equals(ManagerAuth.Auth.CHECK)){ -- Gitblit v1.9.1