漏桶算法

实现思路:

  1. 定义一个数据结构实现漏桶功能,当有外部流量涌入时把流量放入桶中
  2. 实现一个请求处理器,以恒定的速率获取桶中流量进行处理
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
public class LeakyBucketRateLimit implements RateLimit,Runnable{

//出口限制qps
private Integer limitSecond;

//漏桶队列
private BlockingDeque<Thread> leakyBucket;
private ScheduledExecutorService scheduledExecutorService;

public LeakyBucketRateLimit(Integer bucketSize, Integer limitSecond) {
this.limitSecond = limitSecond;
this.leakyBucket = new LinkedBlockingDeque<>(bucketSize);
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
//周期秒数,TimeUnit.NANOSECONDS(毫秒数,1秒=1000*1000*1000)毫微妙
long interval = (1000 * 1000 * 1000) / limitSecond;
scheduledExecutorService.scheduleAtFixedRate(this, 0, interval, TimeUnit.NANOSECONDS);
}

@Override
public boolean canPass() throws RuntimeException {
if(leakyBucket.remainingCapacity() == 0){
throw new RuntimeException();
}
leakyBucket.offer(Thread.currentThread());
LockSupport.park();
return true;
}

@Override
public void run() {
Thread thread = leakyBucket.poll();
if(Objects.nonNull(thread)){
LockSupport.unpark(thread);
}
}

public static void main(String[] args) throws RuntimeException {
LeakyBucketRateLimit leakyBucketRateLimit = new LeakyBucketRateLimit(100, 1);
for (int i = 0; i < 10000; i++){
if(leakyBucketRateLimit.canPass()){
System.out.println("通过第【" + i + "】个请求");
}
}
}
}

漏桶算法
http://www.zivjie.cn/2023/12/09/算法/限流算法/漏桶算法/
作者
Francis
发布于
2023年12月9日
许可协议