6種限流方式

服務限流,是指通過控制請求的速率或次數來達到保護服務的目的,在微服務中,我們通常會將它和熔斷、降級搭配在一起使用,來避免瞬時的大量請求對系統造成負荷,來達到保護服務平穩運行的目的。下面就來看一看常見的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這個腳本,如果有興趣可以看一下具體是如何實現的。

總結

總的來說,要保證系統的抗壓能力,限流是一個必不可少的環節,雖然可能會造成某些用戶的請求被丟棄,但相比於突發流量造成的系統宕機來說,這些損失一般都在可以接受的範圍之內。前面也說過,限流可以結合熔斷、降級一起使用,多管齊下,保證服務的可用性與健壯性。

 

作者:蘇三

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章