com.github.benmanes.caffeine.cache.Caffeine类的使用及代码示例

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

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

Caffeine介绍

[英]A builder of AsyncLoadingCache, LoadingCache, and Cache instances having a combination of the following features:

  • automatic loading of entries into the cache, optionally asynchronously
  • size-based eviction when a maximum is exceeded based on frequency and recency
  • time-based expiration of entries, measured since last access or last write
  • asynchronously refresh when the first stale request for an entry occurs
  • keys automatically wrapped in WeakReference references
  • values automatically wrapped in WeakReference or SoftReference references
  • writes propagated to an external resource
  • notification of evicted (or otherwise removed) entries
  • accumulation of cache access statistics

These features are all optional; caches can be created using all or none of them. By default cache instances created by Caffeine will not perform any type of eviction.

Usage example:

LoadingCache graphs = Caffeine.newBuilder()

The returned cache is implemented as a hash table with similar performance characteristics to ConcurrentHashMap. The asMap view (and its collection views) have weakly consistent iterators. This means that they are safe for concurrent use, but if other threads modify the cache after the iterator is created, it is undefined which of these changes, if any, are reflected in that iterator. These iterators never throw ConcurrentModificationException.

Note: by default, the returned cache uses equality comparisons (the Object#equals method) to determine equality for keys or values. However, if #weakKeys was specified, the cache uses identity ( ==) comparisons instead for keys. Likewise, if #weakValues or #softValues was specified, the cache uses identity comparisons for values.

Entries are automatically evicted from the cache when any of #maximumSize(long), #maximumWeight(long), #expireAfter(Expiry), #expireAfterWrite, #expireAfterAccess, #weakKeys, #weakValues, or #softValues are requested.

If #maximumSize(long) or #maximumWeight(long)is requested entries may be evicted on each cache modification.

If #expireAfter(Expiry), #expireAfterWrite, or #expireAfterAccess is requested entries may be evicted on each cache modification, on occasional cache accesses, or on calls to Cache#cleanUp. Expired entries may be counted by Cache#estimatedSize(), but will never be visible to read or write operations.

If #weakKeys, #weakValues, or #softValues are requested, it is possible for a key or value present in the cache to be reclaimed by the garbage collector. Entries with reclaimed keys or values may be removed from the cache on each cache modification, on occasional cache accesses, or on calls to Cache#cleanUp; such entries may be counted in Cache#estimatedSize(), but will never be visible to read or write operations.

Certain cache configurations will result in the accrual of periodic maintenance tasks which will be performed during write operations, or during occasional read operations in the absence of writes. The Cache#cleanUp method of the returned cache will also perform maintenance, but calling it should not be necessary with a high throughput cache. Only caches built with #maximumSize, #maximumWeight, #expireAfter(Expiry), #expireAfterWrite, #expireAfterAccess, #weakKeys, #weakValues, or #softValues perform periodic maintenance.

The caches produced by Caffeine are serializable, and the deserialized caches retain all the configuration properties of the original cache. Note that the serialized form does not include cache contents, but only configuration.
[中]AsyncLoadingCache、LoadingCache和缓存实例的生成器,具有以下功能的组合:
*自动将条目加载到缓存中(可选异步加载)
*基于频率和最近度超过最大值时基于大小的逐出
*条目的基于时间的过期,自上次访问或上次写入后测量
*第一个过时的条目请求出现时异步刷新
*键自动包装在WeakReference引用中
*值自动包装在WeakReference或SoftReference引用中
*已传播到外部资源的写入
*收回(或以其他方式删除)条目的通知
*缓存访问统计数据的累积
这些功能都是可选的;缓存可以全部使用,也可以不使用。默认情况下,咖啡因创建的缓存实例不会执行任何类型的逐出。
用法示例:

LoadingCache graphs = Caffeine.newBuilder()

返回的缓存作为哈希表实现,具有与ConcurrentHashMap类似的性能特征。asMap视图(及其集合视图)具有弱一致性迭代器。这意味着它们对于并发使用是安全的,但是如果其他线程在创建迭代器后修改缓存,那么这些更改中的哪些(如果有的话)反映在迭代器中是未定义的。这些迭代器从不抛出ConcurrentModificationException。
注意:默认情况下,返回的缓存使用相等比较(Object#equals方法)来确定键或值的相等性。但是,如果指定了#weakKeys,缓存将使用标识(=)比较来代替密钥。同样,如果指定了#weakValues或#softValues,缓存将使用标识比较值。
当请求任何#maximumSize(long)、#maximumWeight(long)、#expireAfter(Expire)、#expireAfterWrite、#expireAfterAccess、#weakKeys、#WeakValue或#SoftValue时,条目将自动从缓存中逐出。
如果请求了#maximumSize(long)或#maximumWeight(long),则每次修改缓存时可能会逐出条目。
如果请求了#expireAfter(Expiry),#expireAfterWrite或#expireAfterAccess,则在每次缓存修改、偶尔缓存访问或调用缓存#清理时,可能会逐出条目。缓存#estimatedSize()可能会对过期条目进行计数,但读或写操作永远看不到过期条目。
如果请求了#weakKeys、#weakValues或#softValues,则缓存中存在的密钥或值可能会被垃圾收集器回收。每次修改缓存、偶尔访问缓存或调用缓存#cleanUp时,可能会从缓存中删除具有回收键或值的条目;这样的条目可以在缓存#estimatedSize()中计数,但在读写操作中永远不可见。
某些缓存配置将导致定期维护任务的累积,这些任务将在写入操作期间执行,或在没有写入的情况下偶尔执行读取操作。返回的缓存的Cache#cleanUp方法也将执行维护,但在高吞吐量缓存中调用它应该是不必要的。只有使用#maximumSize、#maximumWeight、#expireAfter(Expiry)、#expireAfterWrite、#expireAfterAccess、#weakKeys、#WeakValue或#SoftValue构建的缓存才能执行定期维护。
咖啡因产生的缓存是可序列化的,反序列化的缓存保留原始缓存的所有配置属性。请注意,序列化表单不包括缓存内容,只包括配置。

代码示例

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

private static <K, V> ConcurrentMap<K, V> map() {
 return Caffeine.newBuilder()
   .maximumSize(Integer.MAX_VALUE)
   .<K, V>build().asMap();
}

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

RegexStringMatchingStrategy() {
  patternCache = Caffeine.newBuilder()
    .expireAfterWrite(1, TimeUnit.HOURS)
    .build(Pattern::compile);
}

代码示例来源: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: dropwizard/dropwizard

public MustacheViewRenderer() {
  this.factories = Caffeine.newBuilder().build(new CacheLoader<Class<? extends View>, MustacheFactory>() {
    @Override
    public MustacheFactory load(Class<? extends View> key) throws Exception {
      return createNewMustacheFactory(key);
    }
  });
}

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

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

代码示例来源:origin: com.github.ben-manes.caffeine/guava

/**
 * Returns a Caffeine cache wrapped in a Guava {@link Cache} facade.
 *
 * @param builder the configured cache builder
 * @return a cache exposed under the Guava APIs
 */
@Nonnull
public static <K, V, K1 extends K, V1 extends V> Cache<K1, V1> build(
  @Nonnull Caffeine<K, V> builder) {
 return new CaffeinatedGuavaCache<>(builder.build());
}

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

/**
 * Specifies that each entry should be automatically removed from the cache once a fixed duration
 * has elapsed after the entry's creation, or the most recent replacement of its value.
 * <p>
 * Expired entries may be counted in {@link Cache#estimatedSize()}, but will never be visible to
 * read or write operations. Expired entries are cleaned up as part of the routine maintenance
 * described in the class javadoc.
 *
 * @param duration the amount of time after an entry is created that it should be automatically
 *        removed
 * @return this builder instance
 * @throws IllegalArgumentException if the length of time is negative
 * @throws IllegalStateException if the time to live or variable expiration was already set
 */
@Nonnull
public Caffeine<K, V> expireAfterWrite(@Nonnull Duration duration) {
 return expireAfterWrite(duration.toNanos(), TimeUnit.NANOSECONDS);
}

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

/**
 * Specifies that each entry should be automatically removed from the cache once a fixed duration
 * has elapsed after the entry's creation, the most recent replacement of its value, or its last
 * read. Access time is reset by all cache read and write operations (including
 * {@code Cache.asMap().get(Object)} and {@code Cache.asMap().put(K, V)}), but not by operations
 * on the collection-views of {@link Cache#asMap}.
 * <p>
 * Expired entries may be counted in {@link Cache#estimatedSize()}, but will never be visible to
 * read or write operations. Expired entries are cleaned up as part of the routine maintenance
 * described in the class javadoc.
 *
 * @param duration the amount of time after an entry is created that it should be automatically
 *        removed
 * @return this builder instance
 * @throws IllegalArgumentException if the length of time is negative
 * @throws IllegalStateException if the time to idle or variable expiration was already set
 */
@Nonnull
public Caffeine<K, V> expireAfterAccess(@Nonnull Duration duration) {
 return expireAfterAccess(duration.toNanos(), TimeUnit.NANOSECONDS);
}

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

public void testAsMapValues_iteratorRemove() {
  Cache<Integer, Integer> cache = CaffeinatedGuava.build(Caffeine.newBuilder()
    .expireAfterWrite(1000, TimeUnit.MILLISECONDS)
    .executor(MoreExecutors.directExecutor())
    .ticker(fakeTicker::read));

  cache.put(10, 20);
  Iterator<Integer> iterator = cache.asMap().values().iterator();
  iterator.next();
  iterator.remove();

  assertEquals(0, cache.size());
 }
}

代码示例来源: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

@Test
public void expireAfterAccess_large() {
 Caffeine<?, ?> builder = Caffeine.newBuilder()
   .expireAfterAccess(Integer.MAX_VALUE, TimeUnit.NANOSECONDS);
 assertThat(builder.expireAfterAccessNanos, is((long) Integer.MAX_VALUE));
 Expiration<?, ?> expiration = builder.build().policy().expireAfterAccess().get();
 assertThat(expiration.getExpiresAfter(TimeUnit.NANOSECONDS), is((long) Integer.MAX_VALUE));
}

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

public CaffeinePolicy(Config config) {
 policyStats = new PolicyStats("product.Caffeine");
 BasicSettings settings = new BasicSettings(config);
 maximumSize = settings.maximumSize();
 cache = Caffeine.newBuilder()
   .initialCapacity(maximumSize)
   .maximumSize(maximumSize)
   .executor(Runnable::run)
   .build();
}

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

public void testEviction_maxSize() {
 CountingRemovalListener<Integer, Integer> removalListener = countingRemovalListener();
 IdentityLoader<Integer> loader = identityLoader();
 LoadingCache<Integer, Integer> cache = CaffeinatedGuava.build(Caffeine.newBuilder()
   .maximumSize(MAX_SIZE)
   .executor(MoreExecutors.directExecutor())
   .removalListener(removalListener), loader);
 for (int i = 0; i < 2 * MAX_SIZE; i++) {
  cache.getUnchecked(i);
  assertTrue(cache.size() <= MAX_SIZE);
 }
 assertEquals(MAX_SIZE, cache.size());
 assertEquals(MAX_SIZE, removalListener.getCount());
 CacheTesting.checkValidState(cache);
}

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

@Test(expectedExceptions = IllegalArgumentException.class)
public void maximumSize_negative() {
 Caffeine.newBuilder().maximumSize(-1);
}

代码示例来源: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: ben-manes/caffeine

public void testComputeIfAbsentEviction() {
 Cache<String, String> c = CaffeinatedGuava.build(
   Caffeine.newBuilder().executor(MoreExecutors.directExecutor()).maximumSize(1));
 assertThat(c.asMap().computeIfAbsent("hash-1", k -> "")).isEqualTo("");
 assertThat(c.asMap().computeIfAbsent("hash-1", k -> "")).isEqualTo("");
 assertThat(c.asMap().computeIfAbsent("hash-1", k -> "")).isEqualTo("");
 assertThat(c.size()).isEqualTo(1);
 assertThat(c.asMap().computeIfAbsent("hash-2", k -> "")).isEqualTo("");
}

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

@Test(expectedExceptions = IllegalStateException.class)
public void expireAfterWrite_twice() {
 Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.MILLISECONDS)
   .expireAfterWrite(1, TimeUnit.MILLISECONDS);
}

代码示例来源: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

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

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

private static void addBoundedTests(TestSuite suite) throws Exception {
 suite.addTest(MapTestFactory.suite("BoundedCache", () -> {
  Cache<String, String> cache = Caffeine.newBuilder().maximumSize(Long.MAX_VALUE).build();
  return cache.asMap();
 }));
 suite.addTest(MapTestFactory.suite("BoundedAsyncCache", () -> {
  AsyncLoadingCache<String, String> cache = Caffeine.newBuilder()
    .maximumSize(Long.MAX_VALUE)
    .buildAsync(key -> null);
  return cache.synchronous().asMap();
 }));
}

相关文章