我是靠谱客的博主 还单身大雁,最近开发中收集的这篇文章主要介绍java实现 限流算法 漏斗模型,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

package com.example.redis.漏斗限流;
/**
* @Auther: liuyujie
* @Date: 2019/3/4 12:48
* @Description:
*/
public class Funnel {
int capacity;//漏斗容量
double leakingRate;//漏水速度
int leftQuota;//漏斗剩余的量
long leakingTs;//上次漏斗漏水的 时间
public Funnel(int capacity, double leakingRate, int leftQuota, long leakingTs) {
this.capacity = capacity;
this.leakingRate = leakingRate;
this.leftQuota = leftQuota;
this.leakingTs = leakingTs;
}
private void makeSpace(){
long nowTs = System.currentTimeMillis();
long deltaTs = nowTs - this.leakingTs;//这个是间隔的时间
int deltaQuota = (int)(deltaTs*leakingRate);//漏掉的水
if (deltaQuota<0){//间隔时间太长,溢出
this.leftQuota=capacity;
this.leakingTs = nowTs;
return;
}
if (deltaQuota<1){//说明漏的时间不够
return;
}
this.leakingTs = nowTs;
this.leftQuota = this.leftQuota + deltaQuota;
if (this.leftQuota>this.capacity){
this.leftQuota =this.capacity;
}
}
public Boolean water(int quota){
makeSpace();
if (leftQuota >=quota){//表示量充足
leftQuota =
leftQuota-quota;
return true;
}
//剩余量不够
return false;
}
}
//
public class FunnelLimitRate {
private static Map<String,Funnel> funnels = new HashMap<>();
public static void main(String[] args) throws InterruptedException {
String userId= "2019";
String actionKey = "rgister";
int capacity = 10;
double leakingRate= 0.1;
Funnel funnel = funnels.get(userId);
if (funnel==null){
funnel = new Funnel(capacity, leakingRate, 10, System.currentTimeMillis());
}
for (int i = 0; i < 30; i++) {
Boolean water = funnel.water(1);
TimeUnit.MILLISECONDS.sleep(1);
System.out.println(water+ " "+funnel.leftQuota);
}
}
}

 

最后

以上就是还单身大雁为你收集整理的java实现 限流算法 漏斗模型的全部内容,希望文章能够帮你解决java实现 限流算法 漏斗模型所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(45)

评论列表共有 0 条评论

立即
投稿
返回
顶部