JAVA中限制接口流量、并发的方法

  JAVA中限制接口流量可以通过Guava的RateLimiter类或者JDK自带的Semaphore类来实现,两者有点类似,但是也有区别,要根据实际情况使用。简单来说,

RateLimiter类是控制以一定的速率访问接口。

Semaphore类是控制允许同时并发访问接口的数量。

一、RateLimiter类

  RateLimiter翻译过来是速率限制器,使用的是一种叫令牌桶的算法,当线程拿到桶中的令牌时,才可以执行。通过设置每秒生成的令牌数来控制速率。使用例子如下:

 1 public class TestRateLimiter implements Runnable {
 2 
 3     public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 4 
 5     public static final RateLimiter limiter = RateLimiter.create(1); // 允许每秒最多1个任务
 6 
 7     public static void main(String[] arg) {
 8         for (int i = 0; i < 10; i++) {
 9             limiter.acquire(); // 请求令牌,超过许可会被阻塞
10             Thread t = new Thread(new TestRateLimiter());
11             t.start();
12         }
13     }
14 
15     public void run() {
16         System.out.println(sdf.format(new Date()) + " Task End..");
17     }
18 }

二、Semaphore类

  Semaphore翻译过来是信号量,通过设置信号量总数,当线程拿到信号量,才可以执行,当实行完毕再释放信号量。从而控制接口的并发数量。使用例子如下:

 1 public class TestSemaphore implements Runnable {
 2 
 3     public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 4     
 5     public static final Semaphore semaphore = new Semaphore(5, true); // 允许并发的任务量限制为5个
 6     
 7     public static void main(String[] arg) {
 8         for (int i = 0; i < 10; i++) {
 9              Thread t = new Thread(new TestSemaphore());
10              t.start();
11         }
12     }
13 
14     public void run() {
15         try {
16             semaphore.acquire(); // 获取信号量,不足会阻塞
17             System.out.println(sdf.format(new Date()) + " Task Start..");
18             Thread.sleep(5000);
19             System.out.println(sdf.format(new Date()) + " Task End..");
20         } catch (InterruptedException e) {
21             e.printStackTrace();
22         } finally {
23             semaphore.release(); // 释放信号量
24         }
25     }
26 }

  初始化中的第二个参数true代表以公平的方式获取信号量,即先进先出的原则。

原文地址:https://www.cnblogs.com/pcheng/p/8127040.html