zoukankan      html  css  js  c++  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
    
    
  • 相关阅读:
    linux命令
    使用JS实现前端缓存
    git放弃本地修改 强制更新
    java list
    Jquery获取select 控件的change事件时选中的值
    如何将Js代码封装成Jquery插件
    如何获取Iframe的页面控件的值
    简单的百度地图点击获取当前地理坐标
    使用Ajax上传图片到服务器(不刷新页面)
    在微信浏览器中如何让他自动关闭当前页面回到会话框js
  • 原文地址:https://www.cnblogs.com/datiangou/p/10222240.html
Copyright © 2011-2022 走看看