guava限流

guava限流

定义注解

1
2
3
4
5
6
7
8
9

@Inherited
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface GuavaRateLimit {

double limitNum() default 500; //默认每秒放入桶中的token
}

拦截器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

@Component
@Slf4j
public class GuavaRateLimitInterceptor {

private RateLimiter rateLimiter;

@Autowired
private HttpServletResponse response;

//用来存放不同接口的RateLimiter(key为接口名称,value为RateLimiter)
private ConcurrentHashMap<String, RateLimiter> map = new ConcurrentHashMap<>();


@Around("serviceLimit()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
Object obj = null;
//获取拦截的方法名
Signature sig = joinPoint.getSignature();
//获取拦截的方法名
MethodSignature msig = (MethodSignature) sig;
//返回被织入增加处理目标对象
Object target = joinPoint.getTarget();
//为了获取注解信息
Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
//获取注解信息
GuavaRateLimit annotation = currentMethod.getAnnotation(GuavaRateLimit.class);
double limitNum = annotation.limitNum(); //获取注解每秒加入桶中的token
String functionName = msig.getName(); // 注解所在方法名区分不同的限流策略

//获取rateLimiter
if (map.containsKey(functionName)) {
rateLimiter = map.get(functionName);
} else {
map.put(functionName, RateLimiter.create(limitNum));
rateLimiter = map.get(functionName);
}


if (rateLimiter.tryAcquire()) {
//执行方法
obj = joinPoint.proceed();
} else {
//拒绝了请求(服务降级)
String result = JsonUtil.toJson(new MyException(ResultEnum.REQUEST_LIMIT));
log.info("GuavaRateLimit {}", functionName);
outErrorResult(result);
}

return obj;
}

@Pointcut("@annotation(com.meal.aspect.GuavaRateLimit)")
public void serviceLimit() {


}

//将结果返回
public void outErrorResult(String result) {
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
try (ServletOutputStream outputStream = response.getOutputStream()) {
outputStream.write(result.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
}
}

}
文章目录
  1. 1. guava限流
    1. 1.1. 定义注解
    2. 1.2. 拦截器
|