我是靠谱客的博主 还单身大雁,这篇文章主要介绍java实现 限流算法 漏斗模型,现在分享给大家,希望可以做个参考。

复制代码
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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实现内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部