JAVA限流工具类

java

浏览数:303

2019-1-7

片段 1片段 2片段 3


代码

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