JAVA工程限流的方法包括(aop和不是aop形式的)

1、

1.首先接口限流算法:
      1.计数器方式(传统计数器缺点:临界问题 可能违背定义固定速率原则)

     2.令牌桶方式

      3.漏桶方式

     4.应用层限流(Nginx)

2.限流实现:
    2.1. RateLimiter是guava提供的基于令牌桶算法的实现类,可以非常简单的完成限流特技,并且根据系统的实际情况来调整生成token的速率。

    2.2.导入相关依赖包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
 
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
</dependency>
 
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
 
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>20.0</version>
</dependency>
  2.3.代码实现不多说每一步都有注解

    2.3.1 定义注解

    @Inherited
    @Documented
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface RateLimit {
        double limitNum() default 20;  //默认每秒放入桶中的token
    }
    2.3.2 封装定义返回结果

    public class MyResult {
        private Integer status;
        private String msg;
        private List<Object> data;
 
        public MyResult(Integer status, String msg, List<Object> data) {
            this.status = status;
            this.msg = msg;
            this.data = data;
        }
 
        public static MyResult OK(String msg, List<Object> data) {
            return new MyResult(200, msg, data);
        }
 
        public static MyResult Error(Integer status, String msg) {
            return new MyResult(status, msg, null);
        }
2.3.3 aop实现

@Component
@Scope
@Aspect
public class RateLimitAspect {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    //用来存放不同接口的RateLimiter(key为接口名称,value为RateLimiter)
    private ConcurrentHashMap<String, RateLimiter> map = new ConcurrentHashMap<>();
 
    private static ObjectMapper objectMapper = new ObjectMapper();
 
    private RateLimiter rateLimiter;
 
    @Autowired
    private HttpServletResponse response;
 
    @Pointcut("@annotation(com.icat.retalimitaop.annotation.RateLimit)")
    public void serviceLimit() {
    }
 
    @Around("serviceLimit()")
    public Object around(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {
        Object obj = null;
        //获取拦截的方法名
        Signature sig = joinPoint.getSignature();
        //获取拦截的方法名
        MethodSignature msig = (MethodSignature) sig;
        //返回被织入增加处理目标对象
        Object target = joinPoint.getTarget();
        //为了获取注解信息
        Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
        //获取注解信息
        RateLimit annotation = currentMethod.getAnnotation(RateLimit.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);
         }
 
        try {
            if (rateLimiter.tryAcquire()) {
                //执行方法
                obj = joinPoint.proceed();
            } else {
                //拒绝了请求(服务降级)
                String result = objectMapper.writeValueAsString(MyResult.Error(500, "系统繁忙!"));
                log.info("拒绝了请求:" + result);
                outErrorResult(result);
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return obj;
    }
    //将结果返回
    public void outErrorResult(String result) {
        response.setContentType("application/json;charset=UTF-8");
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            outputStream.write(result.getBytes("utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    static {
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }
 
}
3.测试限流
   2个接口设定没秒限流5个和美妙限流10个 
    @RateLimit(limitNum = 5.0)
    public MyResult getResults() {
        log.info("调用了方法getResults");
        return MyResult.OK("调用了方法", null);
    }
 
    @RateLimit(limitNum = 10.0)
    public MyResult getResultTwo() {
        log.info("调用了方法getResultTwo");
        return MyResult.OK("调用了方法getResultTwo", null);

 

最后的方法应该写成下面这个样子才会生效,用main方法不能生效:

@RestController
@Slf4j
public class TestLimitController {

    @GetMapping(value = "/testLimit")
    @RequestLimit
    public R testLimit() {
        log.info("开始测试限流");
        return R.ok("success");
    }
}

 

 

 

2、下面是不使用aop形式的:

 

三、限流工具类RateLimiter

  google开源工具包guava提供了限流工具类RateLimiter,该类基于“令牌桶算法”,非常方便使用。该类的接口具体的使用请参考:RateLimiter使用实践

RateLimiter 使用Demo

?

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

package ratelimite;

import com.google.common.util.concurrent.RateLimiter;

public class RateLimiterDemo {

    public static void main(String[] args) {

        testNoRateLimiter();

        testWithRateLimiter();

    }

    public static void testNoRateLimiter() {

        long start = System.currentTimeMillis();

        for (int i = 0; i < 10; i++) {

            System.out.println("call execute.." + i);

        }

        long end = System.currentTimeMillis();

        System.out.println(end - start);

    }

    public static void testWithRateLimiter() {

        long start = System.currentTimeMillis();

        RateLimiter limiter = RateLimiter.create(10.0);

        // 每秒不超过10个任务被提交

        for (int i = 0; i < 10; i++) {

            limiter.acquire();

            // 请求RateLimiter, 超过permits会被阻塞

            System.out.println("call execute.." + i);

        }

        long end = System.currentTimeMillis();

        System.out.println(end - start);

    }

}

四 Guava并发:ListenableFuture与RateLimiter示例

概念

ListenableFuture顾名思义就是可以监听的Future,它是对java原生Future的扩展增强。我们知道Future表示一个异步计算任务,当任务完成时可以得到计算结果。如果我们希望一旦计算完成就拿到结果展示给用户或者做另外的计算,就必须使用另一个线程不断的查询计算状态。这样做,代码复杂,而且效率低下。使用ListenableFuture Guava帮我们检测Future是否完成了,如果完成就自动调用回调函数,这样可以减少并发程序的复杂度。

推荐使用第二种方法,因为第二种方法可以直接得到Future的返回值,或者处理错误情况。本质上第二种方法是通过调动第一种方法实现的,做了进一步的封装。

另外ListenableFuture还有其他几种内置实现:

SettableFuture:不需要实现一个方法来计算返回值,而只需要返回一个固定值来做为返回值,可以通过程序设置此Future的返回值或者异常信息

CheckedFuture: 这是一个继承自ListenableFuture接口,他提供了checkedGet()方法,此方法在Future执行发生异常时,可以抛出指定类型的异常。

RateLimiter类似于JDK的信号量Semphore,他用来限制对资源并发访问的线程数,本文介绍RateLimiter使用

代码示例

?

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

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.Executors;

import java.util.concurrent.TimeUnit;

import com.google.common.util.concurrent.FutureCallback;

import com.google.common.util.concurrent.Futures;

import com.google.common.util.concurrent.ListenableFuture;

import com.google.common.util.concurrent.ListeningExecutorService;

import com.google.common.util.concurrent.MoreExecutors;

import com.google.common.util.concurrent.RateLimiter;

public class ListenableFutureDemo {

    public static void main(String[] args) {

        testRateLimiter();

        testListenableFuture();

    }

    /**

   * RateLimiter类似于JDK的信号量Semphore,他用来限制对资源并发访问的线程数

   */

    public static void testRateLimiter() {

        ListeningExecutorService executorService = MoreExecutors

                .listeningDecorator(Executors.newCachedThreadPool());

        RateLimiter limiter = RateLimiter.create(5.0);

        // 每秒不超过4个任务被提交

        for (int i = 0; i < 10; i++) {

            limiter.acquire();

            // 请求RateLimiter, 超过permits会被阻塞

            final ListenableFuture<Integer> listenableFuture = executorService

                      .submit(new Task("is "+ i));

        }

    }

    public static void testListenableFuture() {

        ListeningExecutorService executorService = MoreExecutors

                .listeningDecorator(Executors.newCachedThreadPool());

        final ListenableFuture<Integer> listenableFuture = executorService

                .submit(new Task("testListenableFuture"));

        //同步获取调用结果

        try {

            System.out.println(listenableFuture.get());

        }

        catch (InterruptedException e1) {

            e1.printStackTrace();

        }

        catch (ExecutionException e1) {

            e1.printStackTrace();

        }

        //第一种方式

        listenableFuture.addListener(new Runnable() {

            @Override

                  public void run() {

                try {

                    System.out.println("get listenable future's result "

                                  + listenableFuture.get());

                }

                catch (InterruptedException e) {

                    e.printStackTrace();

                }

                catch (ExecutionException e) {

                    e.printStackTrace();

                }

            }

        }

        , executorService);

        //第二种方式

        Futures.addCallback(listenableFuture, new FutureCallback<Integer>() {

            @Override

                  public void onSuccess(Integer result) {

                System.out

                            .println("get listenable future's result with callback "

                                + result);

            }

            @Override

                  public void onFailure(Throwable t) {

                t.printStackTrace();

            }

        }

        );

    }

}

class Task implements Callable<Integer> {

    String str;

    public Task(String str){

        this.str = str;

    }

    @Override

      public Integer call() throws Exception {

        System.out.println("call execute.." + str);

        TimeUnit.SECONDS.sleep(1);

        return 7;

    }

}

Guava版本

?

1

2

3

4

5

<dependency>

      <groupId>com.google.guava</groupId>

      <artifactId>guava</artifactId>

      <version>14.0.1</version>

    </dependency>

 

 

 

3、nginx实现:

https://cloud.tencent.com/developer/article/1368499

https://www.cnblogs.com/biglittleant/p/8979915.html

 

参考的文档如下:

1、 https://blog.csdn.net/qq_39816039/article/details/83988517

2、http://www.manongjc.com/article/59183.html

3、https://www.jb51.net/article/133222.htm

4、http://www.voidcn.com/article/p-wovieveo-bod.html

 

个人git地址:https://github.com/weidadelisq/-middleware/tree/master/spring-boot-mongodbAndRateLimter

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值