1. 程式人生 > >java限流工具類

java限流工具類


程式碼


import com.google.common.util.concurrent.RateLimiter;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 限流工具類
 * @author ZhangShuzheng
 * @date 2018/8/13
 */
public class RateLimiterManager {
 
    private static ConcurrentHashMap<String, RateLimiter> manager = new ConcurrentHashMap<>();
 
    /**
     * 限流
     * @param key 限流key
     * @param qps 頻率:每秒返回鎖次數
     */
    public static void getLock(String key, int qps) {
        ConcurrentHashMap.KeySetView<String, RateLimiter> keys = manager.keySet();
        if (keys.contains(key)) {
            RateLimiter rateLimiter = manager.get(key);
            rateLimiter.acquire();
        } else {
            manager.put(key, RateLimiter.create(qps));
        }
    }
 
}


使用示例


public static void main(String[] args) {
    int count = 100;
 
    ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
            .setNameFormat("demo-pool-%d").build();
 
    ExecutorService threadPoolExecutor = new ThreadPoolExecutor(5, 200,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
 
    threadPoolExecutor.execute(() -> {
        for (int i = 0; i < count; i++) {
            RateLimiterManager.getLock("key1", 10);
            System.out.println("111111111111111111111111");
        }
    });
    threadPoolExecutor.execute(() -> {
        for (int i = 0; i < count; i++) {
            RateLimiterManager.getLock("key2", 1);
            System.out.println("222222222222222222222222");
        }
    });
}


輸出結果


222222222222222222222222
111111111111111111111111
111111111111111111111111
111111111111111111111111
111111111111111111111111
111111111111111111111111
111111111111111111111111
111111111111111111111111
111111111111111111111111
111111111111111111111111
222222222222222222222222
111111111111111111111111
111111111111111111111111
111111111111111111111111
111111111111111111111111
111111111111111111111111
111111111111111111111111
111111111111111111111111
111111111111111111111111