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代表以公平的方式获取信号量,即先进先出的原则。

 

posted @   PC君  阅读(13702)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)

喜欢请打赏

扫描二维码打赏

支付宝打赏

点击右上角即可分享
微信分享提示