背景:通常互联网对外暴露的接口服务都需要做流量限制,以避免被大流量冲击导致服务不可用。常见的情况如秒杀、活动等接口请求往往发生实效较短集中出现在某个时间段。对于对接方的下游客户可能会经常面临的问题:上游接口服务商限制了接口tps请求,下游接口对接方不可避免的会遇到上游接口的限流,通常会返回“调用频率超限…”,这个时候,如果只有一家上游服务商的时候,很容易根据错误码信息区分然后进行请求重试,但是如果在同时对接多家上游的时候就需要我们能够主动性的控制向上游服务商提交的数据流量,对于超过tps限制的流量,直接分发到其他服务商或者排队再次重试以达到正常请求到服务方。
    源码:
    废话不多说:这里直接上代码:

    定义注解:根据注解确定是否限流:

    1. package com.example.ratelimiter.annotation;
    2. import org.redisson.api.RateIntervalUnit;
    3. import java.lang.annotation.*;
    4. /**
    5. * @description: 限流
    6. * @author 98jjy
    7. * @date 2021/8/2
    8. * @version 1.0
    9. */
    10. @Target(value = {ElementType.METHOD})
    11. @Retention(RetentionPolicy.RUNTIME)
    12. @Documented
    13. public @interface RedissonRateLimit {
    14. /**
    15. * key前缀
    16. */
    17. String prefix() default "";
    18. /**
    19. * 限流key
    20. * @return
    21. */
    22. String spel();
    23. /**
    24. * 流速
    25. * @return
    26. */
    27. long rate();
    28. /**
    29. * 频率
    30. * @return
    31. */
    32. long rateInterval();
    33. /**
    34. * 默认时间单位/秒
    35. * @return
    36. */
    37. RateIntervalUnit unit() default RateIntervalUnit.SECONDS;
    38. /**
    39. * -1:默认不过期
    40. * @return
    41. */
    42. int expireSecond() default -1;
    43. /**
    44. * 限流不通过时的处理办法
    45. * @return
    46. */
    47. Class<? extends BaseRateLimitNoPassHandler> noPassHandler() default BaseRateLimitNoPassHandler.class;
    48. /**
    49. * @description: 多个限流Key
    50. * @author 98jjy
    51. * @date 2021/8/2
    52. * @version 1.0
    53. */
    54. @Target(value = {ElementType.METHOD})
    55. @Retention(RetentionPolicy.RUNTIME)
    56. @Documented
    57. public @interface List {
    58. RedissonRateLimit[] value();
    59. }
    60. }

    aop切面处理限流:

    1. package com.example.ratelimiter.config;
    2. import com.example.ratelimiter.annotation.RedissonRateLimit;
    3. import lombok.extern.slf4j.Slf4j;
    4. import org.aspectj.lang.JoinPoint;
    5. import org.aspectj.lang.Signature;
    6. import org.aspectj.lang.annotation.Aspect;
    7. import org.aspectj.lang.annotation.Before;
    8. import org.aspectj.lang.annotation.Pointcut;
    9. import org.aspectj.lang.reflect.MethodSignature;
    10. import org.redisson.api.RRateLimiter;
    11. import org.redisson.api.RateType;
    12. import org.redisson.api.RedissonClient;
    13. import org.springframework.beans.factory.annotation.Autowired;
    14. import org.springframework.core.DefaultParameterNameDiscoverer;
    15. import org.springframework.expression.EvaluationContext;
    16. import org.springframework.expression.spel.standard.SpelExpressionParser;
    17. import org.springframework.expression.spel.support.StandardEvaluationContext;
    18. import org.springframework.stereotype.Component;
    19. import java.lang.reflect.InvocationTargetException;
    20. import java.lang.reflect.Method;
    21. import java.util.concurrent.TimeUnit;
    22. /**
    23. * @description: redssion 令牌桶算法限流
    24. * @author 98jjy
    25. * @date 2021/8/2
    26. * @version 1.0
    27. */
    28. @Component
    29. @Aspect
    30. @Slf4j
    31. public class RedissonRateLimitAspect {
    32. /**
    33. * key 统一前缀
    34. */
    35. private static final String REDISSON_RATE_LIMIT = "redisson_rate_limit:";
    36. /**
    37. * spel表达式解析器
    38. */
    39. private SpelExpressionParser spelExpressionParser = new SpelExpressionParser();
    40. /**
    41. * 参数名发现器
    42. */
    43. private DefaultParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
    44. @Autowired
    45. private RedissonClient redissonClient;
    46. @Pointcut("@annotation(com.example.ratelimiter.annotation.RedissonRateLimit.List)")
    47. public void rateLimitList() {
    48. }
    49. @Pointcut("@annotation(com.example.ratelimiter.annotation.RedissonRateLimit)")
    50. public void rateLimit() {
    51. }
    52. @Before("rateLimit()")
    53. public void beforeAcquire(JoinPoint point) {
    54. log.info("RateLimitAspect acquire");
    55. doAcquire(point);
    56. log.info("RateLimitAspect acquire exit");
    57. }
    58. @Before("rateLimitList()")
    59. public void beforeRateLimit(JoinPoint point) throws Throwable {
    60. log.info("RateLimitAspect acquireList");
    61. doAcquire(point);
    62. log.info("RateLimitAspect acquireList exit");
    63. }
    64. private void doAcquire(JoinPoint jp) {
    65. Signature signature = jp.getSignature();
    66. MethodSignature methodSignature = (MethodSignature) signature;
    67. //获取方法
    68. Method targetMethod = methodSignature.getMethod();
    69. //获取参数对象数组
    70. Object[] args = jp.getArgs();
    71. RedissonRateLimit[] rateLimits = null;
    72. //寻找注解
    73. if (targetMethod.isAnnotationPresent(RedissonRateLimit.List.class)) {
    74. RedissonRateLimit.List list = targetMethod.getAnnotation(RedissonRateLimit.List.class);
    75. rateLimits = list.value();
    76. } else if (targetMethod.isAnnotationPresent(RedissonRateLimit.class)) {
    77. RedissonRateLimit limit = targetMethod.getAnnotation(RedissonRateLimit.class);
    78. rateLimits = new RedissonRateLimit[]{limit};
    79. }
    80. String[] parameterNames = parameterNameDiscoverer.getParameterNames(targetMethod);
    81. for (RedissonRateLimit limit : rateLimits) {
    82. String spel = limit.spel();
    83. // 获得方法参数名数组
    84. if (parameterNames != null && parameterNames.length > 0){
    85. EvaluationContext context = new StandardEvaluationContext();
    86. //获取方法参数值
    87. for (int i = 0; i < args.length; i++) {
    88. // 替换spel里的变量值为实际值, 比如 #user --> user对象
    89. context.setVariable(parameterNames[i],args[i]);
    90. }
    91. // 解析出的key
    92. spel = spelExpressionParser.parseExpression(spel).getValue(context).toString();
    93. }
    94. String key = REDISSON_RATE_LIMIT + limit.prefix() + ":" +spel;
    95. RRateLimiter rRateLimiter = redissonClient.getRateLimiter(key);
    96. rRateLimiter.trySetRate(RateType.OVERALL, limit.rate(), limit.rateInterval(), limit.unit());
    97. if (limit.expireSecond() !=-1) {
    98. //限流器过期自动删除
    99. rRateLimiter.expire(limit.expireSecond(), TimeUnit.SECONDS);
    100. }
    101. if (rRateLimiter.tryAcquire()) {
    102. continue;
    103. } else {
    104. log.warn("rateLimiter:{} no pass", key);
    105. try {
    106. limit.noPassHandler().getConstructor().newInstance().handle(args);
    107. } catch (Exception e) {
    108. log.error("limit.noPassHandler exception:{}", e);
    109. }
    110. throw new RuntimeException("调用频率超限制,请稍后再试");
    111. }
    112. }
    113. }
    114. }

    使用方式:

    1. /**
    2. * 单个参数限流
    3. */
    4. @RedissonRateLimit(prefix = "trade", spel = "#trade.rootMchId", rate = 1, rateInterval = 2,
    5. unit = RateIntervalUnit.SECONDS, expireSecond = 5,
    6. noPassHandler = TradeRateLimitNoPassHandler.class)
    7. @PostMapping("/trade")
    8. public ResponseEntity trade(@RequestBody Trade trade) {
    9. return ResponseEntity.ok("success");
    10. }
    11. /*
    12. * 多个限流,注意顺序,按用户id应该放在前面,总量限流放后面
    13. */
    14. @RedissonRateLimit.List({
    15. @RedissonRateLimit(prefix = "trade:userId", rate = 5, rateInterval = 1, unit = RateIntervalUnit.SECONDS, spel = "#trade.userId", expireSecond = 5),
    16. @RedissonRateLimit(prefix = "trade:rootMchId", rate = 300, rateInterval = 1, unit = RateIntervalUnit.SECONDS, spel = "#trade.rootMchId")})
    17. @PostMapping("/pay")
    18. public ResponseEntity pay(@RequestBody Trade trade){
    19. return ResponseEntity.ok("success");
    20. }