package com.longa.sparks;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.LockSupport;
/**
* 漏桶算法
* -包含的对象:漏桶、漏桶中的元素
*
* @date: 2020/6/16 16:17
* @author: longa
* @version: 1.0
*/
@Slf4j
public class BucketTest {
/**
* 漏桶对象
* -以一定的速率漏出元素
*/
public static class BucketLimit {
AtomicLong nodeId = new AtomicLong(0);
// 漏桶的容量
private int capcity;
// 漏桶的速率
private int flowRate;
private TimeUnit flowUnit;
// 漏桶流出的时间间隔
private long flowRateNanosTime;
/**
* 漏桶的容器
*/
private BlockingQueue<Node> queue;
/**
* 元素请求进入漏桶
*
* @return
*/
public boolean acquire() {
Thread thread = Thread.currentThread();
Node node = new Node(nodeId.incrementAndGet(), thread);
if (this.queue.offer(node)) {
log.info("元素:{}成功进入漏桶", node.id);
LockSupport.park(thread);
return true;
}
return false;
}
public BucketLimit(int capcity, int flowRate, TimeUnit flowUnit) {
this.capcity = capcity;
this.flowRate = flowRate;
this.flowUnit = flowUnit;
this.bucketThreadWork();
}
/**
* 漏桶开始工作的线程
*/
private void bucketThreadWork() {
this.queue = new ArrayBlockingQueue<>(this.capcity);
this.flowRateNanosTime = this.flowUnit.toNanos(1) / this.flowRate;
Thread bucketThread = new Thread(() -> {
this.bucketWork();
});
bucketThread.setName("漏桶线程");
bucketThread.start();
}
/**
* 漏斗
*/
private void bucketWork() {
while (true) {
Node node = this.queue.poll();
if (Objects.nonNull(node)) {
log.info("元素:{}从漏桶通过成功", node.id);
LockSupport.unpark(node.thread);
}
LockSupport.parkNanos(this.flowRateNanosTime);
}
}
/**
* 构建漏桶
*
* @return
*/
public static BucketLimit build(int capcity, int flowRate, TimeUnit flowRateUnit) {
return new BucketLimit(capcity, flowRate, flowRateUnit);
}
}
public static class Node {
private Long id;
private Thread thread;
public Node(Long id, Thread thread) {
this.id = id;
this.thread = thread;
}
}
public static void main(String[] args) {
BucketLimit bucketLimit = BucketLimit.build(10, 60, TimeUnit.SECONDS);
// 请求数量
int requestCount = 20;
for (int i = 1; i <= requestCount; i++) {
new Thread(() -> {
boolean addSuccess = bucketLimit.acquire();
System.out.println(System.currentTimeMillis() + " " + addSuccess);
}).start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
}