RateLimiter 筆記

關於谷歌的RateLimiter限流的使用工具類記錄

package org.limit.example;

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

import java.util.concurrent.ConcurrentHashMap;

/**
 * @Title: RateLimiterUtil
 * @Package: org.limit.example
 * @ProjectName: lruDemo
 * @Description: //TODO
 * @author: xupeng
 * @date: 2019/4/11 16:28
 * @version: V1.0
 */
public class RateLimiterUtil {

    private static double defuntQps = 1.0;

    private static ConcurrentHashMap<String, RateLimiter> limiterMap = new ConcurrentHashMap<String, RateLimiter>();

    public static boolean tryAcquire(String resource, double qps) {
        RateLimiter rateLimiter = limiterMap.get(resource);
        if (rateLimiter == null) {
            rateLimiter = RateLimiter.create(qps);
            RateLimiter rateLitimerByOtherThread = limiterMap.putIfAbsent(resource, rateLimiter);
            if (rateLitimerByOtherThread != null) {
                rateLimiter = rateLitimerByOtherThread;
            }
        }
        rateLimiter.setRate(qps);
        if (rateLimiter.tryAcquire()) {
            return true;
        }
        return false;
    }
    public static boolean tryAcquire(String resource) {
       return tryAcquire(resource,defuntQps);
    }

    public static void main(String[] args)throws Exception{
        String resource="xxx";
        for (int i = 0; i < 100; i++) {
            if (tryAcquire(resource)){
                System.out.println(i);
            }
            Thread.sleep(10);
        }
        Thread.sleep(1000);
        System.out.println("--------------------");
        for (int i = 0; i < 100; i++) {
            if (tryAcquire(resource,10)){
                System.out.println(i);
            }
            Thread.sleep(10);
        }
    }
}

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