java限流工具类
Posted datiangou
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于java限流工具类的主要内容,如果未能解决你的问题,请参考以下文章
solr分布式索引实战分片配置读取:工具类configUtil.java,读取配置代码片段,配置实例
java高并发系列 - 第15天:JUC中的Semaphore,最简单的限流工具类,必备技能