當前位置: 首頁>>代碼示例>>Java>>正文


Java RateLimiter.tryAcquire方法代碼示例

本文整理匯總了Java中com.google.common.util.concurrent.RateLimiter.tryAcquire方法的典型用法代碼示例。如果您正苦於以下問題:Java RateLimiter.tryAcquire方法的具體用法?Java RateLimiter.tryAcquire怎麽用?Java RateLimiter.tryAcquire使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.google.common.util.concurrent.RateLimiter的用法示例。


在下文中一共展示了RateLimiter.tryAcquire方法的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: create

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
public static IFace create(double maxRequestsPerSecond) {
  if (maxRequestsPerSecond <= 0.0) {
    return ALLOW_NONE;
  }

  final RateLimiter rateLimiter = RateLimiter.create(maxRequestsPerSecond);
  return new IFace() {
    @Override
    public boolean allowDequeue(int numJobs) {
      return rateLimiter.tryAcquire(numJobs);
    }

    @Override
    public double getRate() {
      return rateLimiter.getRate();
    }
  };
}
 
開發者ID:pinterest-attic,項目名稱:pinlater,代碼行數:19,代碼來源:QueueRateLimiter.java

示例2: main

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
public static void main(String[] args) {
    try {
        RateLimiter limit = RateLimiter.create(100d);
        PropertyConfigurator.configure("conf/log4j.properties");
        while (true) {
            if (limit.tryAcquire()) {
                final HelloCommand command = new HelloCommand();
                //            System.out.println("result: " + command.execute());
                //            System.out.println("");

                Future<String> future = command.queue();
                System.out.println("result: " + future.get());
                System.out.println("");
            }
        }

        //            Observable<String> observe = command.observe();
        //            observe.asObservable().subscribe((result) -> {
        //                System.out.println(result);
        //            });
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
開發者ID:lemonJun,項目名稱:TakinRPC,代碼行數:25,代碼來源:ClientTest.java

示例3: preHandle

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    if(handler instanceof HandlerMethod){
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        if(method.isAnnotationPresent(Limiter.class)){
            String methodAbsKey = MethodUtil.getAsbMethodCacheKey(method);
            RateLimiter rateLimiter = RateLimiterCache.get(methodAbsKey);
            if(null==rateLimiter){
                return true;
            }
            return rateLimiter.tryAcquire();
        }
    }
    return true;
}
 
開發者ID:0915240,項目名稱:spring-guava-ratelimiter,代碼行數:18,代碼來源:RateLimiterInterceptor.java

示例4: before

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
@Override
public void before(RestyCommand restyCommand) throws FilterException {
    RateLimiter rateLimiter = getRateLimiter(restyCommand);
    if (!rateLimiter.tryAcquire()) {
        throw new RejectException("rejected, exceeded the traffic limit: " + restyCommand.getRestyCommandConfig().getLimit());
    }
}
 
開發者ID:darren-fu,項目名稱:RestyPass,代碼行數:8,代碼來源:TrafficLimitFilter.java

示例5: isRequestPermittedWithCount

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
private boolean isRequestPermittedWithCount(String ip, String endpoint, int count) {
  CacheKey key = new CacheKey(ip, endpoint);
  RateLimiter limit = rateLimits.getUnchecked(key);
  if (limit.tryAcquire()) {
    return true;
  }

  // didn't get it right away, log, wait for 1 second, then fail request
  logger.warn("rate limited; waiting for up to 1 second (ip {}, endpoint {})", ip, endpoint);
  return limit.tryAcquire(count, TimeUnit.SECONDS);
}
 
開發者ID:WeAreWizards,項目名稱:passopolis-server,代碼行數:12,代碼來源:GuavaRequestRateLimiter.java

示例6: checkRateLimit

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
/**
 * Checks if the client belonging to the given {@link RequestContext} has exaggerated the rate limit for a given
 * resource id. If the client has not yet exaggerated the limit, this method will return true. However, if the
 * client has performed more request in the past timeframe than allowed, false will be returned.
 *
 * @param requestContext
 *         The client's request context.
 */
public boolean checkRateLimit(RequestContext requestContext) {
    String clientSpecificRequestKey = requestContext.getClientIdentifier() + "_+_" + requestContext.getResourceId();
    boolean allowRequest = true;
    if ("query".equals(requestContext.getResourceId())) {
        this.rateLimiterMap.computeIfAbsent(clientSpecificRequestKey, c -> RateLimiter.create(CALLS_PER_SECOND));
        RateLimiter rateLimiter = this.rateLimiterMap.get(clientSpecificRequestKey);
        allowRequest = rateLimiter.tryAcquire();
    }
    return allowRequest;
}
 
開發者ID:jhendess,項目名稱:metadict,代碼行數:19,代碼來源:RateControlService.java

示例7: isAllowed

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
public static boolean isAllowed(RateLimiterDescriptor descriptor) {
  if(descriptor.getPermitsPerSecond() <= 0) {
    LOGGER.trace("isAllowed : rate limiting disabled");
    return true;
  }
  try {
    LOGGER.trace("isAllowed : getting ratelimiter for descriptor={}", descriptor);
    RateLimiter r = getOrCreate(descriptor);
    LOGGER.trace("isAllowed : retireved ratelimiter={}, rate={}", r, r.getRate());
    return r.tryAcquire();
  } catch (ExecutionException e) {
    LOGGER.error("isAllowed : Caught exception getting RateLimiter for descriptor : {}", descriptor, e);
    return false;
  }
}
 
開發者ID:magnetsystems,項目名稱:message-server,代碼行數:16,代碼來源:RateLimiterService.java

示例8: requestIntercept

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
/**
 * 請求頻率攔截
 *
 * @param inv
 * @param requestRateLimit
 * @return
 */
private boolean requestIntercept(FixedInvocation inv, EnableRequestRateLimit requestRateLimit) {

    LimitationManager manager = LimitationManager.me();

    RateLimiter limiter = manager.getLimiter(inv.getActionKey());
    if (limiter == null) {
        limiter = manager.initRateLimiter(inv.getActionKey(), requestRateLimit.rate());
    }

    if (limiter.tryAcquire()) {
        return false;
    }

    /**
     * 注解上沒有設置 Action , 使用jboot.properties配置文件的
     */
    if (StringUtils.isBlank(requestRateLimit.limitAction())) {
        //ajax 請求
        if (RequestUtils.isAjaxRequest(inv.getController().getRequest())) {
            inv.getController().renderJson(manager.getAjaxJsonMap());
        }
        //非ajax的正常請求
        else {
            String limitView = manager.getLimitView();
            if (limitView != null) {
                inv.getController().render(limitView);
            } else {
                inv.getController().renderText("reqeust limit.");
            }
        }
    }

    /**
     * 設置了 Action , 用用戶自己配置的
     */
    else {
        switch (requestRateLimit.limitAction()) {
            case LimitAction.JSON:
                inv.getController().renderJson(requestRateLimit.limitContent());
                break;
            case LimitAction.TEXT:
                inv.getController().renderText(requestRateLimit.limitContent());
                break;
            case LimitAction.RENDER:
                inv.getController().render(requestRateLimit.limitContent());
                break;
            case LimitAction.REDIRECT:
                inv.getController().redirect(requestRateLimit.limitContent(), true);
                break;
            default:
                throw new IllegalArgumentException("annotation @EnableRequestRateLimit.limitAction error in "
                        + inv.getController().getClass().getName() + "." + inv.getMethodName()
                        + ",  limitAction support text,json,render,redirect only, not support " + requestRateLimit.limitAction());
        }

    }

    return true;
}
 
開發者ID:yangfuhai,項目名稱:jboot,代碼行數:67,代碼來源:LimitationInterceptor.java


注:本文中的com.google.common.util.concurrent.RateLimiter.tryAcquire方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。