Search in sources :

Example 1 with QuotaResponse

use of com.tencent.polaris.ratelimit.api.rpc.QuotaResponse in project polaris-java by polarismesh.

the class QuotaFlow method getQuota.

public QuotaResponse getQuota(CommonQuotaRequest request) throws PolarisException {
    RateLimitWindow rateLimitWindow = lookupRateLimitWindow(request);
    if (null == rateLimitWindow) {
        // 没有限流规则,直接放通
        return new QuotaResponse(new QuotaResult(QuotaResult.Code.QuotaResultOk, 0, RateLimitConstants.RULE_NOT_EXISTS));
    }
    rateLimitWindow.init();
    return new QuotaResponse(rateLimitWindow.allocateQuota(request.getCount()));
}
Also used : QuotaResult(com.tencent.polaris.api.plugin.ratelimiter.QuotaResult) QuotaResponse(com.tencent.polaris.ratelimit.api.rpc.QuotaResponse)

Example 2 with QuotaResponse

use of com.tencent.polaris.ratelimit.api.rpc.QuotaResponse in project polaris-java by polarismesh.

the class DefaultLimitAPI method getQuota.

@Override
public QuotaResponse getQuota(QuotaRequest request) throws PolarisException {
    checkAvailable("LimitAPI");
    LimitValidator.validateQuotaRequest(request);
    CommonQuotaRequest commonQuotaRequest = new CommonQuotaRequest(request, sdkContext.getConfig());
    QuotaResponse response = quotaFlow.getQuota(commonQuotaRequest);
    reportRateLimit(request, response);
    return response;
}
Also used : CommonQuotaRequest(com.tencent.polaris.ratelimit.client.pojo.CommonQuotaRequest) QuotaResponse(com.tencent.polaris.ratelimit.api.rpc.QuotaResponse)

Example 3 with QuotaResponse

use of com.tencent.polaris.ratelimit.api.rpc.QuotaResponse 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)

Example 4 with QuotaResponse

use of com.tencent.polaris.ratelimit.api.rpc.QuotaResponse in project polaris-java-agent by polarismesh.

the class PolarisOperator method getQuota.

/**
 * 调用LIMIT_API进行服务限流
 *
 * @param count 本次请求的配额
 * @return 是否通过,为false则需要对本次请求限流
 */
public boolean getQuota(String service, String method, Map<String, String> labels, int count) {
    init();
    if (!inited.get()) {
        LOGGER.error("[POLARIS] fail to get quota, service:{}, method:{}, polaris init failed", service, method);
        throw new RuntimeException("polaris init failed");
    }
    QuotaRequest quotaRequest = new QuotaRequest();
    quotaRequest.setNamespace(polarisConfig.getNamespace());
    quotaRequest.setService(service);
    quotaRequest.setMethod(method);
    quotaRequest.setLabels(labels);
    quotaRequest.setCount(count);
    QuotaResponse quota = limitAPI.getQuota(quotaRequest);
    return quota.getCode() == QuotaResultCode.QuotaResultOk;
}
Also used : QuotaRequest(com.tencent.polaris.ratelimit.api.rpc.QuotaRequest) QuotaResponse(com.tencent.polaris.ratelimit.api.rpc.QuotaResponse)

Example 5 with QuotaResponse

use of com.tencent.polaris.ratelimit.api.rpc.QuotaResponse in project spring-cloud-tencent by Tencent.

the class RateLimitScgFilter method doFilter.

@Override
public Mono<Void> doFilter(ServerWebExchange exchange, GatewayFilterChain chain) {
    // get metadata of current thread
    MetadataContext metadataContext = exchange.getAttribute(MetadataConstant.HeaderName.METADATA_CONTEXT);
    String peerNamespace = metadataContext.getSystemMetadata(MetadataConstant.SystemMetadataKey.PEER_NAMESPACE);
    String peerService = metadataContext.getSystemMetadata(MetadataConstant.SystemMetadataKey.PEER_SERVICE);
    String peerPath = metadataContext.getSystemMetadata(MetadataConstant.SystemMetadataKey.PEER_PATH);
    Map<String, String> labels = null;
    if (StringUtils.isNotBlank(peerPath)) {
        labels = new HashMap<>();
        labels.put("method", peerPath);
    }
    try {
        QuotaResponse quotaResponse = QuotaCheckUtils.getQuota(limitAPI, peerNamespace, peerService, 1, labels, null);
        if (quotaResponse.getCode() == QuotaResultCode.QuotaResultLimited) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            DataBuffer dataBuffer = response.bufferFactory().allocateBuffer().write((Consts.QUOTA_LIMITED_INFO + quotaResponse.getInfo()).getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }
    } catch (Throwable throwable) {
        // 限流API调用出现异常,不应该影响业务流程的调用
        LOG.error("fail to rate limit with QuotaRequest[{}-{}-{}].", peerNamespace, peerService, peerPath, throwable);
    }
    return chain.filter(exchange);
}
Also used : MetadataContext(com.tencent.cloud.metadata.context.MetadataContext) QuotaResponse(com.tencent.polaris.ratelimit.api.rpc.QuotaResponse) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Aggregations

QuotaResponse (com.tencent.polaris.ratelimit.api.rpc.QuotaResponse)18 QuotaRequest (com.tencent.polaris.ratelimit.api.rpc.QuotaRequest)8 QuotaResult (com.tencent.polaris.api.plugin.ratelimiter.QuotaResult)5 LimitAPI (com.tencent.polaris.ratelimit.api.core.LimitAPI)4 Before (org.junit.Before)4 RateLimitRuleLabelResolver (com.tencent.cloud.polaris.ratelimit.RateLimitRuleLabelResolver)2 PolarisRateLimitProperties (com.tencent.cloud.polaris.ratelimit.config.PolarisRateLimitProperties)2 Test (org.junit.Test)2 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)2 DataBuffer (org.springframework.core.io.buffer.DataBuffer)2 ServerHttpResponse (org.springframework.http.server.reactive.ServerHttpResponse)2 RequestContext (com.netflix.zuul.context.RequestContext)1 MetadataContext (com.tencent.cloud.metadata.context.MetadataContext)1 CommonQuotaRequest (com.tencent.polaris.ratelimit.client.pojo.CommonQuotaRequest)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 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)1 TooManyRequests (org.springframework.web.client.HttpClientErrorException.TooManyRequests)1