服務限流,是指通過控制請求的速率或次數來達到保護服務的目的,在微服務中,我們通常會將它和熔斷、降級搭配在一起使用,來避免瞬時的大量請求對系統造成負荷,來達到保護服務平穩運行的目的,下面就來看一看常見的6種限流方式,以及它們的實作與使用,
固定視窗演算法
固定視窗演算法通過在單位時間內維護一個計數器,能夠限制在每個固定的時間段內請求通過的次數,以達到限流的效果,

演算法實作起來也比較簡單,可以通過構造方法中的引數指定時間視窗大小以及允許通過的請求數量,當請求進入時先比較當前時間是否超過視窗上邊界,未越界且未超過計數器上限則可以放行請求,
@Slf4j
public class FixedWindowRateLimiter {
// 時間視窗大小,單位毫秒
private long windowSize;
// 允許通過請求數
private int maxRequestCount;
// 當前視窗通過的請求計數
private AtomicInteger count=new AtomicInteger(0);
// 視窗右邊界
private long windowBorder;
public FixedWindowRateLimiter(long windowSize,int maxRequestCount){
this.windowSize = windowSize;
this.maxRequestCount = maxRequestCount;
windowBorder = System.currentTimeMillis()+windowSize;
}
public synchronized boolean tryAcquire(){
long currentTime = System.currentTimeMillis();
if (windowBorder < currentTime){
log.info("window reset");
do {
windowBorder += windowSize;
}while(windowBorder < currentTime);
count=new AtomicInteger(0);
}
if (count.intValue() < maxRequestCount){
count.incrementAndGet();
log.info("tryAcquire success");
return true;
}else {
log.info("tryAcquire fail");
return false;
}
}
}
進行測驗,允許在1000毫秒內通過5個請求:
void test() throws InterruptedException {
FixedWindowRateLimiter fixedWindowRateLimiter
= new FixedWindowRateLimiter(1000, 5);
for (int i = 0; i < 10; i++) {
if (fixedWindowRateLimiter.tryAcquire()) {
System.out.println("執行任務");
}else{
System.out.println("被限流");
TimeUnit.MILLISECONDS.sleep(300);
}
}
}
運行結果:

固定視窗演算法的優點是實作簡單,但是可能無法應對突發流量的情況,比如每秒允許放行100個請求,但是在0.9秒前都沒有請求進來,這就造成了在0.9秒到1秒這段時間內要處理100個請求,而在1秒到1.1秒間可能會再進入100個請求,這就造成了要在0.2秒內處理200個請求,這種流量激增就可能導致后端服務出現例外,

滑動視窗演算法
滑動視窗演算法在固定視窗的基礎上,進行了一定的升級改造,它的演算法的核心在于將時間視窗進行了更精細的分片,將固定視窗分為多個小塊,每次僅滑動一小塊的時間,

并且在每個時間段內都維護了單獨的計數器,每次滑動時,都減去前一個時間塊內的請求數量,并再添加一個新的時間塊到末尾,當時間視窗內所有小時間塊的計數器之和超過了請求閾值時,就會觸發限流操作,
看一下演算法的實作,核心就是通過一個int
型別的陣列回圈使用來維護每個時間片內獨立的計數器:
@Slf4j
public class SlidingWindowRateLimiter {
// 時間視窗大小,單位毫秒
private long windowSize;
// 分片視窗數
private int shardNum;
// 允許通過請求數
private int maxRequestCount;
// 各個視窗內請求計數
private int[] shardRequestCount;
// 請求總數
private int totalCount;
// 當前視窗下標
private int shardId;
// 每個小視窗大小,毫秒
private long tinyWindowSize;
// 視窗右邊界
private long windowBorder;
public SlidingWindowRateLimiter(long windowSize, int shardNum, int maxRequestCount) {
this.windowSize = windowSize;
this.shardNum = shardNum;
this.maxRequestCount = maxRequestCount;
shardRequestCount = new int[shardNum];
tinyWindowSize = windowSize/ shardNum;
windowBorder=System.currentTimeMillis();
}
public synchronized boolean tryAcquire() {
long currentTime = System.currentTimeMillis();
if (currentTime > windowBorder){
do {
shardId = (++shardId) % shardNum;
totalCount -= shardRequestCount[shardId];
shardRequestCount[shardId]=0;
windowBorder += tinyWindowSize;
}while (windowBorder < currentTime);
}
if (totalCount < maxRequestCount){
log.info("tryAcquire success,{}",shardId);
shardRequestCount[shardId]++;
totalCount++;
return true;
}else{
log.info("tryAcquire fail,{}",shardId);
return false;
}
}
}
進行一下測驗,對第一個例子中的規則進行修改,每1秒允許100個請求通過不變,在此基礎上再把每1秒等分為10個0.1秒的視窗,
void test() throws InterruptedException {
SlidingWindowRateLimiter slidingWindowRateLimiter
= new SlidingWindowRateLimiter(1000, 10, 10);
TimeUnit.MILLISECONDS.sleep(800);
for (int i = 0; i < 15; i++) {
boolean acquire = slidingWindowRateLimiter.tryAcquire();
if (acquire){
System.out.println("執行任務");
}else{
System.out.println("被限流");
}
TimeUnit.MILLISECONDS.sleep(10);
}
}
查看運行結果:

程式啟動后,在先休眠了一段時間后再發起請求,可以看到在0.9秒到1秒的時間視窗內放行了6個請求,在1秒到1.1秒內放行了4個請求,隨后就進行了限流,解決了在固定視窗演算法中相鄰時間視窗內允許通過大量請求的問題,
滑動視窗演算法通過將時間片進行分片,對流量的控制更加精細化,但是相應的也會浪費一些存盤空間,用來維護每一塊時間內的單獨計數,并且還沒有解決固定視窗中可能出現的流量激增問題,
漏桶演算法
為了應對流量激增的問題,后續又衍生出了漏桶演算法,用專業一點的詞來說,漏桶演算法能夠進行流量整形和流量控制,
漏桶是一個很形象的比喻,外部請求就像是水一樣不斷注入水桶中,而水桶已經設定好了最大出水速率,漏桶會以這個速率勻速放行請求,而當水超過桶的最大容量后則被丟棄,

看一下代碼實作:
@Slf4j
public class LeakyBucketRateLimiter {
// 桶的容量
private int capacity;
// 桶中現存水量
private AtomicInteger water=new AtomicInteger(0);
// 開始漏水時間
private long leakTimeStamp;
// 水流出的速率,即每秒允許通過的請求數
private int leakRate;
public LeakyBucketRateLimiter(int capacity,int leakRate){
this.capacity=capacity;
this.leakRate=leakRate;
}
public synchronized boolean tryAcquire(){
// 桶中沒有水,重新開始計算
if (water.get()==0){
log.info("start leaking");
leakTimeStamp = System.currentTimeMillis();
water.incrementAndGet();
return water.get() < capacity;
}
// 先漏水,計算剩余水量
long currentTime = System.currentTimeMillis();
int leakedWater= (int) ((currentTime-leakTimeStamp)/1000 * leakRate);
log.info("lastTime:{}, currentTime:{}. LeakedWater:{}",leakTimeStamp,currentTime,leakedWater);
// 可能時間不足,則先不漏水
if (leakedWater != 0){
int leftWater = water.get() - leakedWater;
// 可能水已漏光,設為0
water.set(Math.max(0,leftWater));
leakTimeStamp=System.currentTimeMillis();
}
log.info("剩余容量:{}",capacity-water.get());
if (water.get() < capacity){
log.info("tryAcquire success");
water.incrementAndGet();
return true;
}else {
log.info("tryAcquire fail");
return false;
}
}
}
進行一下測驗,先初始化一個漏桶,設定桶的容量為3,每秒放行1個請求,在代碼中每500毫秒嘗試請求1次:
void test() throws InterruptedException {
LeakyBucketRateLimiter leakyBucketRateLimiter
=new LeakyBucketRateLimiter(3,1);
for (int i = 0; i < 15; i++) {
if (leakyBucketRateLimiter.tryAcquire()) {
System.out.println("執行任務");
}else {
System.out.println("被限流");
}
TimeUnit.MILLISECONDS.sleep(500);
}
}
查看運行結果,按規則進行了放行:

但是,漏桶演算法同樣也有缺點,不管當前系統的負載壓力如何,所有請求都得進行排隊,即使此時服務器的負載處于相對空閑的狀態,這樣會造成系統資源的浪費,由于漏桶的缺陷比較明顯,所以在實際業務場景中,使用的比較少,
令牌桶演算法
令牌桶演算法是基于漏桶演算法的一種改進,主要在于令牌桶演算法能夠在限制服務呼叫的平均速率的同時,還能夠允許一定程度內的突發呼叫,
它的主要思想是系統以恒定的速度生成令牌,并將令牌放入令牌桶中,當令牌桶中滿了的時候,再向其中放入的令牌就會被丟棄,而每次請求進入時,必須從令牌桶中獲取一個令牌,如果沒有獲取到令牌則被限流拒絕,

假設令牌的生成速度是每秒100個,并且第一秒內只使用了70個令牌,那么在第二秒可用的令牌數量就變成了130,在允許的請求范圍上限內,擴大了請求的速率,當然,這里要設定桶容量的上限,避免超出系統能夠承載的最大請求數量,
Guava中的RateLimiter
就是基于令牌桶實作的,可以直接拿來使用,先引入依賴:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>29.0-jre</version>
</dependency>
進行測驗,設定每秒產生5個令牌:
void acquireTest(){
RateLimiter rateLimiter=RateLimiter.create(5);
for (int i = 0; i < 10; i++) {
double time = rateLimiter.acquire();
log.info("等待時間:{}s",time);
}
}
運行結果:

可以看到,每200ms左右產生一個令牌并放行請求,也就是1秒放行5個請求,使用RateLimiter
能夠很好的實作單機的限流,
那么再回到我們前面提到的突發流量情況,令牌桶是怎么解決的呢?RateLimiter
中引入了一個預消費的概念,在原始碼中,有這么一段注釋:
* <p>It is important to note that the number of permits requested <i>never</i> affects the
* throttling of the request itself (an invocation to {@code acquire(1)} and an invocation to {@code
* acquire(1000)} will result in exactly the same throttling, if any), but it affects the throttling
* of the <i>next</i> request. I.e., if an expensive task arrives at an idle RateLimiter, it will be
* granted immediately, but it is the <i>next</i> request that will experience extra throttling,
* thus paying for the cost of the expensive task.
大意就是,申請令牌的數量不同不會影響這個申請令牌這個動作本身的回應時間,acquire(1)
和acquire(1000)
這兩個請求會消耗同樣的時間回傳結果,但是會影響下一個請求的回應時間,
如果一個消耗大量令牌的任務到達空閑的RateLimiter
,會被立即批準執行,但是當下一個請求進來時,將會額外等待一段時間,用來支付前一個請求的時間成本,
至于為什么要這么做,通過舉例來引申一下,當一個系統處于空閑狀態時,突然來了1個需要消耗100個令牌的任務,那么白白等待100秒是毫無意義的浪費資源行為,那么可以先允許它執行,并對后續請求進行限流時間上的延長,以此來達到一個應對突發流量的效果,
看一下具體的代碼示例:
void acquireMultiTest(){
RateLimiter rateLimiter=RateLimiter.create(1);
for (int i = 0; i <3; i++) {
int num = 2 * i + 1;
log.info("獲取{}個令牌", num);
double cost = rateLimiter.acquire(num);
log.info("獲取{}個令牌結束,耗時{}ms",num,cost);
}
}
運行結果:

可以看到,在第二次請求時需要3個令牌,但是并沒有等3秒后才獲取成功,而是在等第一次的1個令牌所需要的1秒償還后,立即獲得了3個令牌得到了放行,同樣,第三次獲取5個令牌時等待的3秒是償還的第二次獲取令牌的時間,償還完成后立即獲取5個新令牌,而并沒有等待全部重新生成完成,
除此之外RateLimiter
還具有平滑預熱功能,下面的代碼就實作了在啟動3秒內,平滑提高令牌發放速率到每秒5個的功能:
void acquireSmoothly(){
RateLimiter rateLimiter=RateLimiter.create(5,3, TimeUnit.SECONDS);
long startTimeStamp = System.currentTimeMillis();
for (int i = 0; i < 15; i++) {
double time = rateLimiter.acquire();
log.info("等待時間:{}s, 總時間:{}ms"
,time,System.currentTimeMillis()-startTimeStamp);
}
}
查看運行結果:

可以看到,令牌發放時間從最開始的500ms多逐漸縮短,在3秒后達到了200ms左右的勻速發放,
總的來說,基于令牌桶實作的RateLimiter
功能還是非常強大的,在限流的基礎上還可以把請求平均分散在各個時間段內,因此在單機情況下它是使用比較廣泛的限流組件,
中間件限流
前面討論的四種方式都是針對單體架構,無法跨JVM進行限流,而在分布式、微服務架構下,可以借助一些中間件進行限,Sentinel是Spring Cloud Alibaba
中常用的熔斷限流組件,為我們提供了開箱即用的限流方法,
使用起來也非常簡單,在service層的方法上添加@SentinelResource
注解,通過value
指定資源名稱,blockHandler
指定一個方法,該方法會在原方法被限流、降級、系統保護時被呼叫,
@Service
public class QueryService {
public static final String KEY="query";
@SentinelResource(value = KEY,
blockHandler ="blockHandlerMethod")
public String query(String name){
return "begin query,name="+name;
}
public String blockHandlerMethod(String name, BlockException e){
e.printStackTrace();
return "blockHandlerMethod for Query : " + name;
}
}
配置限流規則,這里使用直接編碼方式配置,指定QPS到達1時進行限流:
@Component
public class SentinelConfig {
@PostConstruct
private void init(){
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule(QueryService.KEY);
rule.setCount(1);
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
rule.setLimitApp("default");
rules.add(rule);
FlowRuleManager.loadRules(rules);
}
}
在application.yml
中配置sentinel的埠及dashboard地址:
spring:
application:
name: sentinel-test
cloud:
sentinel:
transport:
port: 8719
dashboard: localhost:8088
啟動專案后,啟動sentinel-dashboard
:
java -Dserver.port=8088 -jar sentinel-dashboard-1.8.0.jar
在瀏覽器打開dashboard就可以看見我們設定的流控規則:

進行介面測驗,在超過QPS指定的限制后,則會執行blockHandler()
方法中的邏輯:

Sentinel在微服務架構下得到了廣泛的使用,能夠提供可靠的集群流量控制、服務斷路等功能,在使用中,限流可以結合熔斷、降級一起使用,成為有效應對三高系統的三板斧,來保證服務的穩定性,
網關限流
網關限流也是目前比較流行的一種方式,這里我們介紹采用Spring Cloud的gateway
組件進行限流的方式,
在專案中引入依賴,gateway的限流實際使用的是Redis加lua腳本的方式實作的令牌桶,因此還需要引入redis的相關依賴:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
對gateway進行配置,主要就是配一下令牌的生成速率、令牌桶的存盤量上限,以及用于限流的鍵的決議器,這里設定的桶上限為2,每秒填充1個令牌:
spring:
application:
name: gateway-test
cloud:
gateway:
routes:
- id: limit_route
uri: lb://sentinel-test
predicates:
- Path=/sentinel-test/**
filters:
- name: RequestRateLimiter
args:
# 令牌桶每秒填充平均速率
redis-rate-limiter.replenishRate: 1
# 令牌桶上限
redis-rate-limiter.burstCapacity: 2
# 指定決議器,使用spEl運算式按beanName從spring容器中獲取
key-resolver: "#{@pathKeyResolver}"
- StripPrefix=1
redis:
host: 127.0.0.1
port: 6379
我們使用請求的路徑作為限流的鍵,撰寫對應的決議器:
@Slf4j
@Component
public class PathKeyResolver implements KeyResolver {
public Mono<String> resolve(ServerWebExchange exchange) {
String path = exchange.getRequest().getPath().toString();
log.info("Request path: {}",path);
return Mono.just(path);
}
}
啟動gateway,使用jmeter進行測驗,設定請求間隔為500ms,因為每秒生成一個令牌,所以后期達到了每兩個請求放行1個的限流效果,在被限流的情況下,http請求會回傳429狀態碼,

除了上面的根據請求路徑限流外,我們還可以靈活設定各種限流的維度,例如根據請求header中攜帶的用戶資訊、或是攜帶的引數等等,當然,如果不想用gateway自帶的這個Redis的限流器的話,我們也可以自己實作RateLimiter
介面來實作一個自己的限流工具,
gateway實作限流的關鍵是spring-cloud-gateway-core
包中的RedisRateLimiter
類,以及META-INF/scripts
中的request-rate-limiter.lua
這個腳本,如果有興趣可以看一下具體是如何實作的,
總結
總的來說,要保證系統的抗壓能力,限流是一個必不可少的環節,雖然可能會造成某些用戶的請求被丟棄,但相比于突發流量造成的系統宕機來說,這些損失一般都在可以接受的范圍之內,前面也說過,限流可以結合熔斷、降級一起使用,多管齊下,保證服務的可用性與健壯性,
作者:蘇三
本文來自博客園,作者:古道輕風,轉載請注明原文鏈接:https://www.cnblogs.com/88223100/p/6-current-limiting-methods.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/554302.html
標籤:Java
上一篇:day08-SpringCloud Gateway-服務網關
下一篇:返回列表