Example usage for com.google.common.util.concurrent RateLimiter create

List of usage examples for com.google.common.util.concurrent RateLimiter create

Introduction

In this page you can find the example usage for com.google.common.util.concurrent RateLimiter create.

Prototype

public static RateLimiter create(double permitsPerSecond, long warmupPeriod, TimeUnit unit) 

Source Link

Document

Creates a RateLimiter with the specified stable throughput, given as "permits per second" (commonly referred to as QPS, queries per second), and a warmup period, during which the RateLimiter smoothly ramps up its rate, until it reaches its maximum rate at the end of the period (as long as there are enough requests to saturate it).

Usage

From source file:load.SinkerRunner.java

public SinkerRunner(Queue<Packet> queue, SinkerMBean input) {
    this.queue = queue;
    this.input = input;
    this.limiter = RateLimiter.create(input.getRate(), 1, TimeUnit.MICROSECONDS);
    this.prevRate = input.getRate();
}

From source file:load.loadGeneratorRunner.java

public loadGeneratorRunner(Queue<net.Packet> queue, LoadGeneratorMBean input) {
    this.limiter = RateLimiter.create(input.getRate(), 1, TimeUnit.MICROSECONDS);
    this.queue = queue;
    this.input = input;
    this.prevRate = input.getRate();
}

From source file:ren.hankai.cordwood.web.security.support.DefaultAccessLimiter.java

@Override
public boolean handleAccess(HandlerExecutionChain requestHandler, HttpServletResponse response) {
    final Object obj = requestHandler.getHandler();
    if (null != obj) {
        if (obj instanceof HandlerMethod) {
            final HandlerMethod hm = (HandlerMethod) obj;
            final Stabilized anno = getStabilizations(hm);
            // ??
            if (null != anno) {
                // ????
                RateLimitInfo limitInfo = rateLimitMappings.get(hm);
                if (null == limitInfo) {
                    // ???
                    final RateLimiter limiter = RateLimiter.create(anno.maxQps(), anno.warmupPeriod(),
                            TimeUnit.SECONDS);
                    limitInfo = new RateLimitInfo(limiter);
                    rateLimitMappings.put(hm, limitInfo);
                } else {
                    logger.debug(String.format(
                            "Access hit limit mapping, selected handler mapping was:\n\n %s\n", hm.toString()));
                }//  www.java 2 s.  c  o  m
                if (limitInfo.isFused(anno)) {
                    // 
                    logger.debug("Fused, service will be unavailable temporarily.");
                    response.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value());
                    return false;
                } else {
                    // ???
                    final boolean success = limitInfo.getLimiter().tryAcquire(1, anno.timeout(),
                            TimeUnit.MICROSECONDS);
                    if (success) {
                        limitInfo.resetFailures(); // ????
                        logger.debug("Token acquired, service is now available.");
                    } else {
                        logger.debug("Failed to acquire token, service will be unavailable temporarily.");
                        limitInfo.addFailures(); // ?
                        response.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value());
                        return false;
                    }
                }
            }
        }
    }
    return true;
}

From source file:org.apache.omid.benchmarks.tso.RawTxRunner.java

RawTxRunner(final TSOServerBenchmarkConfig expConfig) throws IOException, InterruptedException {

    // Injector configuration
    List<Module> guiceModules = new ArrayList<>();
    guiceModules.add(new Module() {
        @Override/*from   w w w  . j a  v  a 2 s. c o m*/
        public void configure(Binder binder) {
            binder.bind(MetricsRegistry.class).toInstance(expConfig.getMetrics());
        }
    });
    guiceModules.add(expConfig.getCommitTableStoreModule());
    Injector injector = Guice.createInjector(guiceModules);

    // Tx Runner config
    this.writesetSize = expConfig.getWritesetSize();
    this.fixedWriteSetSize = expConfig.isFixedWritesetSize();
    this.commitDelayInMs = expConfig.getCommitDelayInMs();
    this.percentageOfReadOnlyTxs = expConfig.getPercentageOfReadOnlyTxs();
    this.cellIdGenerator = expConfig.getCellIdGenerator();
    this.randomGen = new Random(System.currentTimeMillis() * txRunnerId); // to make it channel dependent

    int txRateInReqPerSec = expConfig.getTxRateInRequestPerSecond();
    long warmUpPeriodInSecs = expConfig.getWarmUpPeriodInSecs();

    LOG.info("TxRunner-{} [ Tx Rate (Req per Sec) -> {} ]", txRunnerId, txRateInReqPerSec);
    LOG.info("TxRunner-{} [ Warm Up Period -> {} Secs ]", txRunnerId, warmUpPeriodInSecs);
    LOG.info("TxRunner-{} [ Cell Id Distribution Generator -> {} ]", txRunnerId,
            expConfig.getCellIdGenerator().getClass());
    LOG.info("TxRunner-{} [ Max Tx Size -> {} Fixed: {} ]", txRunnerId, writesetSize, fixedWriteSetSize);
    LOG.info("TxRunner-{} [ Commit delay -> {} Ms ]", txRunnerId, commitDelayInMs);
    LOG.info("TxRunner-{} [ % of Read-Only Tx -> {} % ]", txRunnerId, percentageOfReadOnlyTxs);

    // Commit table client initialization
    CommitTable commitTable = injector.getInstance(CommitTable.class);
    this.commitTableClient = commitTable.getClient();

    // Stat initialization
    MetricsRegistry metrics = injector.getInstance(MetricsRegistry.class);
    String hostName = InetAddress.getLocalHost().getHostName();
    this.timestampTimer = metrics.timer(name("tx_runner", Integer.toString(txRunnerId), hostName, "timestamp"));
    this.commitTimer = metrics.timer(name("tx_runner", Integer.toString(txRunnerId), hostName, "commit"));
    this.abortTimer = metrics.timer(name("tx_runner", Integer.toString(txRunnerId), hostName, "abort"));
    this.errorCounter = metrics.counter(name("tx_runner", Integer.toString(txRunnerId), hostName, "errors"));
    LOG.info("TxRunner-{} [ Metrics provider module -> {} ]", txRunnerId, expConfig.getMetrics().getClass());

    // TSO Client initialization
    OmidClientConfiguration tsoClientConf = expConfig.getOmidClientConfiguration();
    this.tsoClient = TSOClient.newInstance(tsoClientConf);
    LOG.info("TxRunner-{} [ Connection Type {}/Connection String {} ]", txRunnerId,
            tsoClientConf.getConnectionType(), tsoClientConf.getConnectionString());

    // Limiter for configured request per second
    this.rateLimiter = RateLimiter.create((double) txRateInReqPerSec, warmUpPeriodInSecs, TimeUnit.SECONDS);
}

From source file:com.tinspx.util.concurrent.LimitedExecutorService.java

public static Supplier<RateLimiter> rateLimiterSupplier(final double permitsPerSecond, final long warmupPeriod,
        final TimeUnit unit) {
    checkArgument(permitsPerSecond > 0.0 && !Double.isNaN(permitsPerSecond),
            "permitsPerSecond must be positive (%s)", permitsPerSecond);
    checkArgument(warmupPeriod >= 0, "warmupPeriod must not be negative (%s)", warmupPeriod);
    checkNotNull(unit);/*from  w  w  w. ja v  a  2  s  .co  m*/
    return new Supplier<RateLimiter>() {
        @Override
        public RateLimiter get() {
            return RateLimiter.create(permitsPerSecond, warmupPeriod, unit);
        }
    };
}