Search in sources :

Example 1 with InitResult

use of com.tencent.polaris.ratelimit.example.utils.LimitExampleUtils.InitResult in project polaris-java by polarismesh.

the class RateLimitExample method main.

public static void main(String[] args) throws Exception {
    InitResult initResult = LimitExampleUtils.initRateLimitConfiguration(args);
    String namespace = initResult.getNamespace();
    String service = initResult.getService();
    int concurrency = initResult.getConcurrency();
    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(concurrency);
    // 注意:使用本地限流时,限流阈值计数器会存放在LimitAPI实例内部,无法跨实例共享,因此LimitAPI建议通过进程单例模式使用
    try (LimitAPI limitAPI = LimitAPIFactory.createLimitAPI()) {
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                QuotaRequest quotaRequest = new QuotaRequest();
                quotaRequest.setNamespace(namespace);
                quotaRequest.setService(service);
                quotaRequest.setMethod("echo");
                quotaRequest.setCount(1);
                QuotaResponse quotaResponse = limitAPI.getQuota(quotaRequest);
                System.out.println("quotaResponse is " + quotaResponse.getCode());
            }
        };
        List<ScheduledFuture<?>> futures = new ArrayList<>();
        for (int i = 0; i < concurrency; i++) {
            ScheduledFuture<?> scheduledFuture = executorService.scheduleWithFixedDelay(runnable, 10 + i, 500, TimeUnit.MILLISECONDS);
            futures.add(scheduledFuture);
        }
        Thread.sleep(500000);
        for (ScheduledFuture<?> future : futures) {
            future.cancel(true);
        }
    }
    executorService.shutdown();
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) InitResult(com.tencent.polaris.ratelimit.example.utils.LimitExampleUtils.InitResult) ArrayList(java.util.ArrayList) QuotaRequest(com.tencent.polaris.ratelimit.api.rpc.QuotaRequest) LimitAPI(com.tencent.polaris.ratelimit.api.core.LimitAPI) QuotaResponse(com.tencent.polaris.ratelimit.api.rpc.QuotaResponse) ScheduledFuture(java.util.concurrent.ScheduledFuture)

Aggregations

LimitAPI (com.tencent.polaris.ratelimit.api.core.LimitAPI)1 QuotaRequest (com.tencent.polaris.ratelimit.api.rpc.QuotaRequest)1 QuotaResponse (com.tencent.polaris.ratelimit.api.rpc.QuotaResponse)1 InitResult (com.tencent.polaris.ratelimit.example.utils.LimitExampleUtils.InitResult)1 ArrayList (java.util.ArrayList)1 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)1 ScheduledFuture (java.util.concurrent.ScheduledFuture)1