|
@@ -0,0 +1,38 @@
|
|
|
+package edu.travel.guava.aop;
|
|
|
+
|
|
|
+import com.google.common.util.concurrent.RateLimiter;
|
|
|
+import org.aspectj.lang.ProceedingJoinPoint;
|
|
|
+import org.aspectj.lang.annotation.Around;
|
|
|
+import org.aspectj.lang.annotation.Aspect;
|
|
|
+import org.aspectj.lang.annotation.Pointcut;
|
|
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+import org.springframework.web.context.request.RequestAttributes;
|
|
|
+import org.springframework.web.context.request.RequestContextHolder;
|
|
|
+import org.springframework.web.context.request.ServletRequestAttributes;
|
|
|
+
|
|
|
+import javax.servlet.http.HttpServletResponse;
|
|
|
+
|
|
|
+@Aspect
|
|
|
+@Component
|
|
|
+public class RateLimitAspect {
|
|
|
+ @Autowired
|
|
|
+ private RateLimiter rateLimiter;
|
|
|
+ @Pointcut("@annotation(edu.travel.guava.annotation.RateLimitAble)")
|
|
|
+ public void pointCut() {}
|
|
|
+
|
|
|
+ @Around("pointCut()")
|
|
|
+ public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
|
|
|
+ if (rateLimiter.tryAcquire()) {
|
|
|
+ return joinPoint.proceed(joinPoint.getArgs());
|
|
|
+ }else {
|
|
|
+ RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
|
|
|
+ HttpServletResponse response = ((ServletRequestAttributes)requestAttributes).getResponse();
|
|
|
+ response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
|
|
|
+ response.setContentType("application/json");
|
|
|
+ response.setCharacterEncoding("UTF-8");
|
|
|
+ response.getWriter().write("每秒请求数量达到最高,目前是熔断降级");
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|