java 흐름 제한 도구 클래스

2269 단어
코드

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

다음으로 전송:https://www.cnblogs.com/datiangou/p/10222240.html

좋은 웹페이지 즐겨찾기