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


Java RateLimiter.create方法代碼示例

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


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

示例1: initRateLimiter

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
public RateLimiter initRateLimiter(String target, double rate) {
    RateLimiter limiter = requestRateLimiterMap.get(target);
    if (limiter == null) {
        limiter = RateLimiter.create(rate);
        requestRateLimiterMap.put(target, limiter);
        return limiter;
    }

    if (limiter.getRate() == rate) {
        return limiter;
    }

    limiter.setRate(rate);
    requestRateLimiterMap.put(target, limiter);

    return limiter;
}
 
開發者ID:yangfuhai,項目名稱:jboot,代碼行數:18,代碼來源:LimitationManager.java

示例2: RedisThrottler

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
RedisThrottler(
        RedisThrottlerConfig config,
        RedisAppender appender,
        boolean ignoreExceptions,
        boolean debugEnabled) {
    this.config = config;
    this.appender = appender;
    this.ignoreExceptions = ignoreExceptions;
    this.buffer = new ArrayBlockingQueue<>(config.getBufferSize());
    this.batch = new byte[config.getBatchSize()][];
    this.flushTrigger = createFlushTrigger();
    this.eventRateLimiter = config.getMaxEventCountPerSecond() > 0 ? RateLimiter.create(config.getMaxEventCountPerSecond()) : null;
    this.byteRateLimiter = config.getMaxByteCountPerSecond() > 0 ? RateLimiter.create(config.getMaxByteCountPerSecond()) : null;
    this.logger = new DebugLogger(RedisThrottler.class, debugEnabled);
    this.jmxBeanName = createJmxBeanName();
}
 
開發者ID:vy,項目名稱:log4j2-redis-appender,代碼行數:17,代碼來源:RedisThrottler.java

示例3: 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

示例4: setParent

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
/**
 * @param parent the parent to set.
 */
@Override
public void setParent(Channel parent)
{
   super.setParent(parent);

   UserQuotas quotas = this.getUserQuotas();

   if (quotas != null)
   {
      if (quotas.getMaxBandwidth() != null)
      {
         this.rateLimiter =
            RateLimiter.create(quotas.getMaxBandwidth().intValue());
      }

      if (quotas.getMaxSize() != null)
      {
         this.maxAllowedPermits = quotas.getMaxSize().longValue();
      }
   }
}
 
開發者ID:SentinelDataHub,項目名稱:dhus-core,代碼行數:25,代碼來源:ChannelFlow.java

示例5: getUserByFeignBatch

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
@Override
public BaseResponse<UserResVO> getUserByFeignBatch(@RequestBody UserReqVO userReqVO) {
    //調用遠程服務
    OrderNoReqVO vo = new OrderNoReqVO() ;
    vo.setReqNo(userReqVO.getReqNo());

    RateLimiter limiter = RateLimiter.create(2.0) ;
    //批量調用
    for (int i = 0 ;i< COUNT ; i++){
        double acquire = limiter.acquire();
        logger.debug("獲取令牌成功!,消耗=" + acquire);
        BaseResponse<OrderNoResVO> orderNo = orderServiceClient.getOrderNo(vo);
        logger.debug("遠程返回:"+JSON.toJSONString(orderNo));
    }

    UserRes userRes = new UserRes() ;
    userRes.setUserId(123);
    userRes.setUserName("張三");

    userRes.setReqNo(userReqVO.getReqNo());
    userRes.setCode(StatusEnum.SUCCESS.getCode());
    userRes.setMessage("成功");

    return userRes ;
}
 
開發者ID:crossoverJie,項目名稱:springboot-cloud,代碼行數:26,代碼來源:UserController.java

示例6: RemoteConfigLongPollService

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
/**
 * Constructor.
 */
public RemoteConfigLongPollService() {
  m_longPollFailSchedulePolicyInSecond = new ExponentialSchedulePolicy(1, 120); //in second
  m_longPollingStopped = new AtomicBoolean(false);
  m_longPollingService = Executors.newSingleThreadExecutor(
      ApolloThreadFactory.create("RemoteConfigLongPollService", true));
  m_longPollStarted = new AtomicBoolean(false);
  m_longPollNamespaces =
      Multimaps.synchronizedSetMultimap(HashMultimap.<String, RemoteConfigRepository>create());
  m_notifications = Maps.newConcurrentMap();
  m_remoteNotificationMessages = Maps.newConcurrentMap();
  m_responseType = new TypeToken<List<ApolloConfigNotification>>() {
  }.getType();
  gson = new Gson();
  m_configUtil = ApolloInjector.getInstance(ConfigUtil.class);
  m_httpUtil = ApolloInjector.getInstance(HttpUtil.class);
  m_serviceLocator = ApolloInjector.getInstance(ConfigServiceLocator.class);
  m_longPollRateLimiter = RateLimiter.create(m_configUtil.getLongPollQPS());
}
 
開發者ID:dewey-its,項目名稱:apollo-custom,代碼行數:22,代碼來源:RemoteConfigLongPollService.java

示例7: RemoteConfigRepository

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
/**
 * Constructor.
 *
 * @param namespace the namespace
 */
public RemoteConfigRepository(String namespace) {
  m_namespace = namespace;
  m_configCache = new AtomicReference<>();
  m_configUtil = ApolloInjector.getInstance(ConfigUtil.class);
  m_httpUtil = ApolloInjector.getInstance(HttpUtil.class);
  m_serviceLocator = ApolloInjector.getInstance(ConfigServiceLocator.class);
  remoteConfigLongPollService = ApolloInjector.getInstance(RemoteConfigLongPollService.class);
  m_longPollServiceDto = new AtomicReference<>();
  m_remoteMessages = new AtomicReference<>();
  m_loadConfigRateLimiter = RateLimiter.create(m_configUtil.getLoadConfigQPS());
  m_configNeedForceRefresh = new AtomicBoolean(true);
  m_loadConfigFailSchedulePolicy = new ExponentialSchedulePolicy(m_configUtil.getOnErrorRetryInterval(),
      m_configUtil.getOnErrorRetryInterval() * 8);
  gson = new Gson();
  this.trySync();
  this.schedulePeriodicRefresh();
  this.scheduleLongPollingRefresh();
}
 
開發者ID:ctripcorp,項目名稱:apollo,代碼行數:24,代碼來源:RemoteConfigRepository.java

示例8: TradeUnit

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
public TradeUnit(final TradeConfiguration tradeConf, final PulsarClient client,
        final ProducerConfiguration producerConf, final ConsumerConfiguration consumerConf,
        final Map<Integer, byte[]> payloadCache) throws Exception {
    consumerFuture = client.subscribeAsync(tradeConf.topic, "Subscriber-" + tradeConf.topic, consumerConf);
    this.payload = new AtomicReference<>();
    this.producerConf = producerConf;
    this.payloadCache = payloadCache;
    this.client = client;
    topic = tradeConf.topic;

    // Add a byte[] of the appropriate size if it is not already present
    // in the cache.
    this.payload.set(payloadCache.computeIfAbsent(tradeConf.size, byte[]::new));
    rateLimiter = RateLimiter.create(tradeConf.rate);
    stop = new AtomicBoolean(false);
}
 
開發者ID:apache,項目名稱:incubator-pulsar,代碼行數:17,代碼來源:LoadSimulationClient.java

示例9: ManagedLedgerImpl

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
public ManagedLedgerImpl(ManagedLedgerFactoryImpl factory, BookKeeper bookKeeper, MetaStore store,
        ManagedLedgerConfig config, ScheduledExecutorService scheduledExecutor, OrderedSafeExecutor orderedExecutor,
        final String name) {
    this.factory = factory;
    this.bookKeeper = bookKeeper;
    this.config = config;
    this.store = store;
    this.name = name;
    this.scheduledExecutor = scheduledExecutor;
    this.executor = orderedExecutor;
    TOTAL_SIZE_UPDATER.set(this, 0);
    NUMBER_OF_ENTRIES_UPDATER.set(this, 0);
    ENTRIES_ADDED_COUNTER_UPDATER.set(this, 0);
    STATE_UPDATER.set(this, State.None);
    this.ledgersStat = null;
    this.mbean = new ManagedLedgerMBeanImpl(this);
    this.entryCache = factory.getEntryCacheManager().getEntryCache(this);
    this.waitingCursors = Queues.newConcurrentLinkedQueue();
    this.uninitializedCursors = Maps.newHashMap();
    this.updateCursorRateLimit = RateLimiter.create(1);

    // Get the next rollover time. Add a random value upto 5% to avoid rollover multiple ledgers at the same time
    this.maximumRolloverTimeMs = (long) (config.getMaximumRolloverTimeMs() * (1 + random.nextDouble() * 5 / 100.0));
}
 
開發者ID:apache,項目名稱:incubator-pulsar,代碼行數:25,代碼來源:ManagedLedgerImpl.java

示例10: ManagedCursorImpl

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
ManagedCursorImpl(BookKeeper bookkeeper, ManagedLedgerConfig config, ManagedLedgerImpl ledger, String cursorName) {
    this.bookkeeper = bookkeeper;
    this.config = config;
    this.ledger = ledger;
    this.name = cursorName;
    STATE_UPDATER.set(this, State.Uninitialized);
    PENDING_MARK_DELETED_SUBMITTED_COUNT_UPDATER.set(this, 0);
    PENDING_READ_OPS_UPDATER.set(this, 0);
    RESET_CURSOR_IN_PROGRESS_UPDATER.set(this, FALSE);
    WAITING_READ_OP_UPDATER.set(this, null);
    this.lastLedgerSwitchTimestamp = System.currentTimeMillis();

    if (config.getThrottleMarkDelete() > 0.0) {
        markDeleteLimiter = RateLimiter.create(config.getThrottleMarkDelete());
    } else {
        // Disable mark-delete rate limiter
        markDeleteLimiter = null;
    }
}
 
開發者ID:apache,項目名稱:incubator-pulsar,代碼行數:20,代碼來源:ManagedCursorImpl.java

示例11: waitTaskConsumption

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
protected void waitTaskConsumption(boolean returnIfStopped, boolean waitForRunning) {
	RateLimiter rateLimiter = RateLimiter.create(1);
	int tryCount = 0;
	while (true) {
		tryCount++;
		rateLimiter.acquire();
		
		if (
				// if returnIfStopped == true, we consider that wait is done
				(returnIfStopped || manager.isActive())
				&& manager.getNumberOfWaitingTasks() == 0
				// if we don't wait for running, ignore manager.getNumberOfRunningTasks()
				&& (!waitForRunning || manager.getNumberOfRunningTasks() == 0)) {
			break;
		}
		
		if (tryCount > 10) {
			throw new IllegalStateException(MessageFormat.format("Task queue not empty after {0} tries.", tryCount));
		}
	}
}
 
開發者ID:openwide-java,項目名稱:owsi-core-parent,代碼行數:22,代碼來源:TestTaskManagement.java

示例12: writeCache

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
@Provides
@ElasticsearchScope
public RateLimitedCache<Pair<String, HashCode>> writeCache(final HeroicReporter reporter) {
    final Cache<Pair<String, HashCode>, Boolean> cache = CacheBuilder
        .newBuilder()
        .concurrencyLevel(4)
        .expireAfterWrite(writeCacheDurationMinutes, TimeUnit.MINUTES)
        .build();

    if (writesPerSecond <= 0d) {
        return new DisabledRateLimitedCache<>(cache.asMap());
    }

    reporter.registerCacheSize("elasticsearch-suggest-write-through", cache::size);

    return new DefaultRateLimitedCache<>(cache.asMap(),
        RateLimiter.create(writesPerSecond, rateLimitSlowStartSeconds, TimeUnit.SECONDS));
}
 
開發者ID:spotify,項目名稱:heroic,代碼行數:19,代碼來源:ElasticsearchSuggestModule.java

示例13: StackdriverWriter

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
/**
 * Constructs a {@link StackdriverWriter}.
 *
 * <p>The monitoringClient must have read and write permissions to the Cloud Monitoring API v3 on
 * the provided project.
 */
public StackdriverWriter(
    Monitoring monitoringClient,
    String project,
    MonitoredResource monitoredResource,
    int maxQps,
    int maxPointsPerRequest) {
  this.monitoringClient = checkNotNull(monitoringClient);
  this.projectResource = "projects/" + checkNotNull(project);
  this.monitoredResource = monitoredResource;
  this.maxPointsPerRequest = maxPointsPerRequest;
  this.timeSeriesBuffer = new ArrayDeque<>(maxPointsPerRequest);
  this.rateLimiter = RateLimiter.create(maxQps);
}
 
開發者ID:google,項目名稱:java-monitoring-client-library,代碼行數:20,代碼來源:StackdriverWriter.java

示例14: ServiceRateLimiter

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
public ServiceRateLimiter(MetricRegistry metrics, XConfig config) {
  this.reqs = metrics.meter(name(Router.class, "requests", "Rate"));
  this.timer = metrics.timer("Request Latency");
  this.config = config;
  this.globalHardLimiter = RateLimiter.create(config.globalHardReqPerSec());
  this.globalSoftLimiter = RateLimiter.create(config.globalSoftReqPerSec());

  softRateLimitHasher =
      buildHasher(softLimiterMap, config.getRateLimiterPoolSize(), config.softReqPerSec());
  hardRateLimitHasher =
      buildHasher(hardLimiterMap, config.getRateLimiterPoolSize(), config.hardReqPerSec());
}
 
開發者ID:Nordstrom,項目名稱:xrpc,代碼行數:13,代碼來源:ServiceRateLimiter.java

示例15: VulnersService

import com.google.common.util.concurrent.RateLimiter; //導入方法依賴的package包/類
public VulnersService(BurpExtender burpExtender, IBurpExtenderCallbacks callbacks, IExtensionHelpers helpers, Map<String, Domain> domains, TabComponent tabComponent) {
    this.burpExtender = burpExtender;
    this.callbacks = callbacks;
    this.helpers = helpers;
    this.domains = domains;
    this.tabComponent = tabComponent;
    this.rateLimiter = RateLimiter.create(4.0);  // Count of max RPS

    Unirest.setDefaultHeader("user-agent", "vulners-burpscanner-v-1.1");
    Unirest.setAsyncHttpClient(HttpClient.createSSLClient());
}
 
開發者ID:vulnersCom,項目名稱:burp-vulners-scanner,代碼行數:12,代碼來源:VulnersService.java


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