javaredis限流_Redis——限流算法之滑动窗口、漏斗限流的原理及java实现

在redis中可以⽤zset数据结构来实现这个功能:
⽤唯⼀的id作为zset的key,可以是user_id + action_key ,value是当前操作时间戳。每次新的操作请求进来时,先判断当前时间窗⼝内记录的操作次数 count,⼩于阈值max则允许进⾏操作,超过阈值则进⾏限流。同时对时间窗⼝之外的数据进⾏清理,节省内存。
Response count = ard(key);
<();
pipe.close();
() <= maxCount;
}
复制代码
zset中的value没有特殊含义,只是⽤来保证每次操作都是唯⼀的能够被zset记录。
lg km380漏⽃限流
顾名思义就是⽤⼀个漏⽃来存储(记录请求),⼀边向漏⽃⾥⾯加请求⼀边将请求漏出去。漏⽃的漏嘴有⼀个流⽔速率,表⽰单位时间内流出的⽔量(数据量),当加⽔的速率(单位时间加进去的请求)⼩于流⽔速率时漏⽃永远不会满。
我们不⽤时刻记录==漏⽔==,只需记录上⼀次漏⽔的开始时间,当⼀个请求进来时,我们只需要计算上次漏⽔的时间到当前时间⼀共漏出的数据量count,⽤这上次漏⽔⾄今的数据总量减去count,了,来判断漏⽃是否溢出
漏⽃算法的Java实现:
public class FunnelRateLimiter {undefined
藤井瑞希
static class Funnel {undefined
// 漏⽃⼤⼩
int capacity;
// 漏嘴流⽔速率
float leakingRate;
// 漏⽃剩余容量
int leftQuota;
// 上⼀次漏⽔时间
long leakingTs;
public Funnel(int capacity, float leakingRate) {undefined
this.capacity = capacity;
this.leakingRate = leakingRate;
this.leftQuota = capacity;
// 初始化时指定当前时间为第⼀次漏⽔时间
this.leakingTs = System.currentTimeMillis();
}
void makeSpace() {undefined
long nowTs = System.currentTimeMillis();
long deltaTs = nowTs - leakingTs;
// 流⽔速率 * 时间,计算这段时间流出的数据总量
int deltaQuota = (int) (deltaTs * leakingRate);
if (deltaQuota < 0) { // 间隔时间太长,整数数字过⼤溢出
this.leftQuota = capacity;
this.leakingTs = nowTs;
return;
至于夏水襄陵
}
二外法语
if (deltaQuota < 1) { // 腾出空间太⼩,最⼩单位是 1
return;
}
this.leftQuota += deltaQuota;
this.leakingTs = nowTs;
// 流出的数据总量超过漏⽃容量,说明漏⽃在某些时间是空的,没有实际数据漏出
if (this.leftQuota > this.capacity) {undefined
this.leftQuota = this.capacity;
}
}
boolean watering(int quota) {undefined
makeSpace();
//⽐较当前加⼊的数据量和漏⽃剩余容量
if (this.leftQuota >= quota) {undefined国民党王牌军覆灭记
this.leftQuota -= quota;
return true;
}
return false;
}
}
// ⽤⼀个HashMap存储漏⽃数据
液体树脂private Map funnels = new HashMap<>();
public boolean isActionAllowed(String userId, String actionKey, int capacity, float leakingRate){undefined // 唯⼀key
String key = String.format("%s:%s", userId, actionKey);
Funnel funnel = (key);
if (funnel == null) {undefined

本文发布于:2024-09-24 11:29:02,感谢您对本站的认可!

本文链接:https://www.17tex.com/xueshu/187539.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:时间   请求   操作   速率
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议