高并发情况下的漏桶算法(javascript版)

发布时间 2023-12-12 13:30:51作者: mrt_yy
class LeakyBucket { //高并发情况下的漏桶算法
				constructor(capacity, leakRate) { // 创建一个容量为capacity,每秒漏水量为leakRate的漏桶
					this.capacity = capacity;
					this.leakRate = leakRate;
					this.water = 0;
					this.lastLeakTime = Date.now();
				}
				allow(waterAmount) {
					const currentTime = Date.now();
					const leakAmount = (currentTime - this.lastLeakTime) / 1000 * this.leakRate;
					this.water = Math.max(0, this.water - leakAmount);
					this.lastLeakTime = currentTime;
					if (this.water + waterAmount > this.capacity) {
						return false; // bucket overflow  
					} else {
						this.water += waterAmount;
						return true;
					}
				}
			}
			const bucket = new LeakyBucket(5, 1);
			document.getElementById("asdf").onclick = function () {
				if(bucket.allow(1)){
					console.log("走请求");
				}else{
					console.log("歇一会");
				}
			}