当前位置:网站首页>guava RateLimiter均匀限流
guava RateLimiter均匀限流
2022-08-11 04:59:00 【pilaf1990】
guava的pom依赖:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
guava采用了令牌桶算法,即以恒定的速率向桶里放令牌,需要通过RateLimiter的acquire方法阻塞式地拿到令牌之后,才可以继续执行任务(比如请求处理等代码),从而达到均匀限流的目的。
guava的RateLimiter限流器创建方法:
RateLimiter.create(5);
其中create方法的参数表示的是1秒钟内允许获取的令牌数量,即QPS。
create方法内部默认会创建SmoothBursty类型的RateLimiter,它是比较均匀的将QPS分散到1秒内的各个时间段。
比如这儿的create(5),表示1秒钟内只能获取5个令牌,并且前0.2秒内只能获取1个,0.2-0.4秒内也只能获取1个,0.4-0.6秒,0.6-0.8秒,0.8-1.0秒也分别能获取1个令牌。这样做的好处是防止请求不均匀,如果在1秒的开始就把令牌都用完了,那么在上一秒结束的时候也获得了令牌,则上一秒结束和这一秒的开始所在的秒内获取的令牌数就超过了QPS的定义的允许获得的令牌数了。
下面看一段代码:
public class RateLimiterDemo {
public static void main(String[] args) throws Exception{
RateLimiter rateLimiter = RateLimiter.create(5);
for (int i = 0; i < 10; i++) {
System.out.println(rateLimiter.tryAcquire());
}
}
}
执行后输出
true
false
false
false
false
false
false
false
false
false
只有第一次tryAcquire返回true,后边几次都返回false,即只有第一次尝试获取令牌的时候获取成功了,后边的9次都没有获取到,因为for循环执行很快,基本上都在前0.2秒内去尝试获取令牌,也就只能获取到1个(5个令牌分散在1秒内,前0.2秒只能获取一个令牌)。
将for循环中加入睡眠:
public class RateLimiterDemo {
public static void main(String[] args) throws Exception{
RateLimiter rateLimiter = RateLimiter.create(5);
for (int i = 0; i < 10; i++) {
Thread.sleep(200);
System.out.println(rateLimiter.tryAcquire());
}
}
}
输出的结果是10个true:
true
true
true
true
true
true
true
true
true
true
也就是说每次都获取到了令牌。因为每次获取后都睡眠了200毫秒,1秒除以200毫秒等于5,所以每个时间段都能获取到令牌(我们通过create(5)限制了一秒内能获取到的令牌数就是5,会分散到5个时间段内)。
边栏推荐
- K8s Review Notes 7--K8S Implementation of Redis Standalone and Redis-cluster
- 交换机和路由器技术-24-OSPF单区域配置
- Switch and Router Technology - 32 - Named ACL
- Application of Identification Cryptography in IMS Network
- The priority queue
- The shortest path out of the maze
- Switch and Router Technology-35-NAT to PAT
- 02.折叠隐藏文字
- 交换机和路由器技术-25-OSPF多区域配置
- 智能指针笔记
猜你喜欢
随机推荐
leetcode 9. 回文数
C语言题解:谁是凶手!
Switch and Router Technology-27-OSPF Route Redistribution
[Note] Is the value of BatchSize the bigger the better?
Switch and Router Technology - 36-Port Mirroring
Harvesting of radio frequency energy
ALSA音频架构 -- aplay播放流程分析
2021年网络规划设计师下午案例题
Let's talk programming languages together
Switch and Router Technology - 28 - NSSA Areas for OSPF
Australia cyberspace security system construction
走出迷宫的最短路径
Selenium自动化测试框架工作原理你明白了吗?
In the closing pages/uninstall (unload) sends a request to the server before the document
Redis deletes keys in batches according to regular rules
FPGA engineer interview questions collection 111~120
梅克尔工作室--OpenEuler培训笔记(1)
CAD2020 打开错误报告 e06d7363h Exception at 13644F69h
Bubble sort and heap sort
C语句:数据存储








