com.github.benmanes.caffeine.cache.Caffeine.recordStats()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(11.2k)|赞(0)|评价(0)|浏览(146)

本文整理了Java中com.github.benmanes.caffeine.cache.Caffeine.recordStats()方法的一些代码示例,展示了Caffeine.recordStats()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Caffeine.recordStats()方法的具体详情如下:
包路径:com.github.benmanes.caffeine.cache.Caffeine
类名称:Caffeine
方法名:recordStats

Caffeine.recordStats介绍

[英]Enables the accumulation of CacheStats during the operation of the cache. Without this Cache#stats will return zero for all statistics. Note that recording statistics requires bookkeeping to be performed with each operation, and thus imposes a performance penalty on cache operation.
[中]在缓存操作期间启用CacheStats的累积。如果没有此缓存,所有统计数据的统计数据都将返回零。请注意,记录统计信息需要对每个操作执行簿记,因此会对缓存操作造成性能损失。

代码示例

代码示例来源:origin: dropwizard/dropwizard

/**
 * Creates a new cached authorizer.
 *
 * @param metricRegistry the application's registry of metrics
 * @param authorizer     the underlying authorizer
 * @param builder        a {@link CaffeineSpec}
 */
public CachingAuthorizer(
  final MetricRegistry metricRegistry,
  final Authorizer<P> authorizer,
  final Caffeine<Object, Object> builder) {
  this.underlying = authorizer;
  this.cacheMisses = metricRegistry.meter(name(authorizer.getClass(), "cache-misses"));
  this.getsTimer = metricRegistry.timer(name(authorizer.getClass(), "gets"));
  this.cache = builder.recordStats().build(key -> {
    cacheMisses.mark();
    return underlying.authorize(key.left, key.right);
  });
}

代码示例来源:origin: dropwizard/dropwizard

/**
 * Creates a new cached authenticator.
 *
 * @param metricRegistry the application's registry of metrics
 * @param authenticator  the underlying authenticator
 * @param builder        a {@link Caffeine}
 */
public CachingAuthenticator(final MetricRegistry metricRegistry,
              final Authenticator<C, P> authenticator,
              final Caffeine<Object, Object> builder) {
  this.cacheMisses = metricRegistry.meter(name(authenticator.getClass(), "cache-misses"));
  this.gets = metricRegistry.timer(name(authenticator.getClass(), "gets"));
  this.cache = builder.recordStats().build(key -> {
    cacheMisses.mark();
    final Optional<P> optPrincipal = authenticator.authenticate(key);
    if (!optPrincipal.isPresent()) {
      // Prevent caching of unknown credentials
      throw new InvalidCredentialsException();
    }
    return optPrincipal;
  });
}

代码示例来源:origin: ben-manes/caffeine

@Test
public void recordStats_twice() {
 Supplier<StatsCounter> supplier = () -> statsCounter;
 Runnable[] tasks = {
   () -> Caffeine.newBuilder().recordStats().recordStats(),
   () -> Caffeine.newBuilder().recordStats(supplier).recordStats(),
   () -> Caffeine.newBuilder().recordStats().recordStats(supplier),
   () -> Caffeine.newBuilder().recordStats(supplier).recordStats(supplier),
 };
 for (Runnable task : tasks) {
  try {
   task.run();
   Assert.fail();
  } catch (IllegalStateException expected) {}
 }
}

代码示例来源:origin: line/armeria

private static <T> Cache<PathMappingContext, T> buildCache(String spec) {
  return Caffeine.from(spec).recordStats().build();
}

代码示例来源:origin: ben-manes/caffeine

@Test(expectedExceptions = NullPointerException.class)
public void recordStats_null() {
 Caffeine.newBuilder().recordStats(null);
}

代码示例来源:origin: ben-manes/caffeine

@Test
public void recordStats() {
 Caffeine<?, ?> builder = Caffeine.newBuilder().recordStats();
 assertThat(builder.statsCounterSupplier, is(Caffeine.ENABLED_STATS_COUNTER_SUPPLIER));
 builder.build();
}

代码示例来源:origin: ben-manes/caffeine

private Caffeine<Object, Object> createCacheBuilder() {
 return Caffeine.newBuilder().executor(MoreExecutors.directExecutor()).recordStats();
}

代码示例来源:origin: ben-manes/caffeine

@Override public LoadingCache<Object, Object> apply(
   Caffeine<Object, Object> builder) {
  return CaffeinatedGuava.build(builder.recordStats(), identityLoader());
 }
});

代码示例来源:origin: ben-manes/caffeine

@Test
public void recordStats_custom() {
 Supplier<StatsCounter> supplier = () -> statsCounter;
 Caffeine<?, ?> builder = Caffeine.newBuilder().recordStats(supplier);
 builder.statsCounterSupplier.get().recordEviction(1);
 verify(statsCounter).recordEviction(1);
 builder.build();
}

代码示例来源:origin: ben-manes/caffeine

@Test
public void configured() {
 Caffeine<Object, Object> configured = Caffeine.newBuilder()
   .initialCapacity(1).weakKeys()
   .expireAfterAccess(1, TimeUnit.SECONDS).expireAfterWrite(1, TimeUnit.SECONDS)
   .removalListener((k, v, c) -> {}).recordStats();
 assertThat(configured.build(), is(not(nullValue())));
 assertThat(configured.buildAsync(), is(not(nullValue())));
 assertThat(configured.build(loader), is(not(nullValue())));
 assertThat(configured.buildAsync(loader), is(not(nullValue())));
 assertThat(configured.refreshAfterWrite(1, TimeUnit.SECONDS).toString(),
   is(not(Caffeine.newBuilder().toString())));
 assertThat(Caffeine.newBuilder().maximumSize(1).toString(),
   is(not(Caffeine.newBuilder().maximumWeight(1).toString())));
}

代码示例来源:origin: apache/incubator-druid

public static CaffeineCache create(final CaffeineCacheConfig config, final Executor executor)
{
 Caffeine<Object, Object> builder = Caffeine.newBuilder().recordStats();
 if (config.getExpireAfter() >= 0) {
  builder
    .expireAfterAccess(config.getExpireAfter(), TimeUnit.MILLISECONDS);
 }
 if (config.getSizeInBytes() >= 0) {
  builder.maximumWeight(config.getSizeInBytes());
 } else {
  builder.maximumWeight(Math.min(MAX_DEFAULT_BYTES, JvmUtils.getRuntimeInfo().getMaxHeapSizeBytes() / 10));
 }
 builder
   .weigher((NamedKey key, byte[] value) -> value.length
                        + key.key.length
                        + key.namespace.length() * Character.BYTES
                        + FIXED_COST)
   .executor(executor);
 return new CaffeineCache(builder.build(), config);
}

代码示例来源:origin: line/armeria

private static Cache<PathAndEncoding, AggregatedHttpFile> newCache(HttpFileServiceConfig config) {
  final Caffeine<Object, Object> b = Caffeine.newBuilder();
  b.maximumSize(config.maxCacheEntries())
   .recordStats()
   .removalListener((RemovalListener<PathAndEncoding, AggregatedHttpFile>) (key, value, cause) -> {
     if (value != null) {
       final HttpData content = value.content();
       if (content instanceof ByteBufHolder) {
         ((ByteBufHolder) content).release();
       }
     }
   });
  return b.build();
}

代码示例来源:origin: ben-manes/caffeine

@SuppressWarnings("FutureReturnValueIgnored")
public Stresser() {
 ThreadFactory threadFactory = new ThreadFactoryBuilder()
   .setPriority(Thread.MAX_PRIORITY)
   .setDaemon(true)
   .build();
 Executors.newSingleThreadScheduledExecutor(threadFactory)
   .scheduleAtFixedRate(this::status, STATUS_INTERVAL, STATUS_INTERVAL, SECONDS);
 cache = Caffeine.newBuilder()
   .maximumSize(operation.maxEntries)
   .recordStats()
   .build(key -> key);
 local = (BoundedLocalCache<Integer, Integer>) cache.asMap();
 ints = new Integer[TOTAL_KEYS];
 Arrays.setAll(ints, key -> {
  cache.put(key, key);
  return key;
 });
 cache.cleanUp();
 stopwatch = Stopwatch.createStarted();
 status();
}

代码示例来源:origin: ben-manes/caffeine

public void testParse_recordStats() {
 CaffeineSpec spec = parse("recordStats");
 assertTrue(spec.recordStats);
 assertCaffeineEquivalence(Caffeine.newBuilder().recordStats(), Caffeine.from(spec));
}

代码示例来源:origin: ben-manes/caffeine

public void testBulkLoadInterruptedException() {
 Exception e = new InterruptedException();
 CacheLoader<Object, Object> loader = exceptionLoader(e);
 LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder()
   .recordStats().executor(MoreExecutors.directExecutor()), bulkLoader(loader));
 CacheStats stats = cache.stats();
 assertEquals(0, stats.missCount());
 assertEquals(0, stats.loadSuccessCount());
 assertEquals(0, stats.loadExceptionCount());
 assertEquals(0, stats.hitCount());
 try {
  cache.getAll(asList(new Object()));
  fail();
 } catch (ExecutionException expected) {
  assertSame(e, expected.getCause());
 }
 assertTrue(Thread.interrupted());
 stats = cache.stats();
 assertEquals(1, stats.missCount());
 assertEquals(0, stats.loadSuccessCount());
 assertEquals(1, stats.loadExceptionCount());
 assertEquals(0, stats.hitCount());
}

代码示例来源:origin: ben-manes/caffeine

public void testBulkLoadCheckedException() {
 Exception e = new Exception();
 CacheLoader<Object, Object> loader = exceptionLoader(e);
 LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder()
   .recordStats(), bulkLoader(loader));
 CacheStats stats = cache.stats();
 assertEquals(0, stats.missCount());
 assertEquals(0, stats.loadSuccessCount());
 assertEquals(0, stats.loadExceptionCount());
 assertEquals(0, stats.hitCount());
 try {
  cache.getAll(asList(new Object()));
  fail();
 } catch (ExecutionException expected) {
  assertSame(e, expected.getCause());
 }
 stats = cache.stats();
 assertEquals(1, stats.missCount());
 assertEquals(0, stats.loadSuccessCount());
 assertEquals(1, stats.loadExceptionCount());
 assertEquals(0, stats.hitCount());
}

代码示例来源:origin: ben-manes/caffeine

public void testBulkLoadNull() throws ExecutionException {
 LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder()
   .recordStats().executor(MoreExecutors.directExecutor()), bulkLoader(constantLoader(null)));
 CacheStats stats = cache.stats();
 assertEquals(0, stats.missCount());
 assertEquals(0, stats.loadSuccessCount());
 assertEquals(0, stats.loadExceptionCount());
 assertEquals(0, stats.hitCount());
 try {
  cache.getAll(asList(new Object()));
  fail();
 } catch (InvalidCacheLoadException expected) {}
 stats = cache.stats();
 assertEquals(1, stats.missCount());
 assertEquals(0, stats.loadSuccessCount());
 assertEquals(1, stats.loadExceptionCount());
 assertEquals(0, stats.hitCount());
}

代码示例来源:origin: ben-manes/caffeine

public void testBulkLoadUncheckedException() throws ExecutionException {
 Exception e = new RuntimeException();
 CacheLoader<Object, Object> loader = exceptionLoader(e);
 LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder()
   .recordStats(), bulkLoader(loader));
 CacheStats stats = cache.stats();
 assertEquals(0, stats.missCount());
 assertEquals(0, stats.loadSuccessCount());
 assertEquals(0, stats.loadExceptionCount());
 assertEquals(0, stats.hitCount());
 try {
  cache.getAll(asList(new Object()));
  fail();
 } catch (UncheckedExecutionException expected) {
  assertSame(e, expected.getCause());
 }
 stats = cache.stats();
 assertEquals(1, stats.missCount());
 assertEquals(0, stats.loadSuccessCount());
 assertEquals(1, stats.loadExceptionCount());
 assertEquals(0, stats.hitCount());
}

代码示例来源:origin: ben-manes/caffeine

public void testBulkLoadError() throws ExecutionException {
 Error e = new Error();
 CacheLoader<Object, Object> loader = errorLoader(e);
 LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder()
   .recordStats(), bulkLoader(loader));
 CacheStats stats = cache.stats();
 assertEquals(0, stats.missCount());
 assertEquals(0, stats.loadSuccessCount());
 assertEquals(0, stats.loadExceptionCount());
 assertEquals(0, stats.hitCount());
 try {
  cache.getAll(asList(new Object()));
  fail();
 } catch (ExecutionError expected) {
  assertSame(e, expected.getCause());
 }
 stats = cache.stats();
 assertEquals(1, stats.missCount());
 assertEquals(0, stats.loadSuccessCount());
 assertEquals(1, stats.loadExceptionCount());
 assertEquals(0, stats.hitCount());
}

代码示例来源:origin: ben-manes/caffeine

public void testBulkLoadNullMap() throws ExecutionException {
 LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder()
   .recordStats(), new CacheLoader<Object, Object>() {
    @Override
    public Object load(Object key) {
     throw new AssertionError();
    }
    @Override
    public Map<Object, Object> loadAll(Iterable<? extends Object> keys) {
     return null;
    }
   });
 CacheStats stats = cache.stats();
 assertEquals(0, stats.missCount());
 assertEquals(0, stats.loadSuccessCount());
 assertEquals(0, stats.loadExceptionCount());
 assertEquals(0, stats.hitCount());
 try {
  cache.getAll(asList(new Object()));
  fail();
 } catch (InvalidCacheLoadException expected) {}
 stats = cache.stats();
 assertEquals(1, stats.missCount());
 assertEquals(0, stats.loadSuccessCount());
 assertEquals(1, stats.loadExceptionCount());
 assertEquals(0, stats.hitCount());
}

相关文章