1. 程式人生 > >使用Guava的RateLimiter做限流

使用Guava的RateLimiter做限流

RateLimiter 從概念上來講,速率限制器會在可配置的速率下分配許可證。如果必要的話,每個acquire() 會阻塞當前執行緒直到許可證可用後獲取該許可證。一旦獲取到許可證,不需要再釋放許可證。

簡單示例

 public static void main(String[] args) {
        RateLimiter rateLimiter = RateLimiter.create(2);
        System.out.println(rateLimiter.acquire(5));
        System.out.println(rateLimiter.acquire(2));
        System.out.println(rateLimiter.acquire(1));
    }

多執行緒測試

package com.ky.common;

import com.google.common.util.concurrent.RateLimiter;
import com.ky.core.utils.date.DateUtils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: fang
 * @Date: 2018/11/14 17:04
 */
public class Test {
    private static final RateLimiter rateLimiter = RateLimiter.create(2);

    public static class WorkerThread implements Runnable {
        int i;

        WorkerThread(int i){
            this.i = i;
        }
        
        @Override
        public void run() {
            send(i);
        }
    }

    public static void send(int i){
        rateLimiter.acquire();
        System.out.println("thread"+i+",當前時間:"+ DateUtils.getNowTime());
    }

    public static void run(){
        ExecutorService executor = Executors.newFixedThreadPool(50);
        for (int i = 0; i < 50; i++) {
            Runnable runnable = new WorkerThread(i);
            executor.execute(runnable);
        }
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");
    }

    public static void main(String args[]) {
        run();
    }
}