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

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

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

Cache介绍

[英]A semi-persistent mapping from keys to values. Cache entries are manually added using #get(Object,Function) or #put(Object,Object), and are stored in the cache until either evicted or manually invalidated.

Implementations of this interface are expected to be thread-safe, and can be safely accessed by multiple concurrent threads.
[中]从键到值的半持久映射。使用#get(对象、函数)或#put(对象、对象)手动添加缓存项,并将其存储在缓存中,直到逐出或手动使其无效。
该接口的实现应该是线程安全的,并且可以由多个并发线程安全地访问。

代码示例

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

@Override
public void record(long key) {
 Object value = cache.getIfPresent(key);
 if (value == null) {
  if (cache.estimatedSize() == maximumSize) {
   policyStats.recordEviction();
  }
  cache.put(key, key);
  policyStats.recordMiss();
 } else {
  policyStats.recordHit();
 }
}

代码示例来源:origin: spring-projects/spring-framework

@Override
@Nullable
public ValueWrapper putIfAbsent(Object key, @Nullable final Object value) {
  PutIfAbsentFunction callable = new PutIfAbsentFunction(value);
  Object result = this.cache.get(key, callable);
  return (callable.called ? null : toValueWrapper(result));
}

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

private void checkContainsInOrder(Cache<Integer, Integer> cache, Integer... expect) {
 cache.cleanUp();
 List<Integer> evictionList = ImmutableList.copyOf(
   cache.policy().eviction().get().coldest(Integer.MAX_VALUE).keySet());
 assertThat(cache.asMap().size(), is(equalTo(expect.length)));
 assertThat(cache.asMap().keySet(), containsInAnyOrder(expect));
 assertThat(evictionList, is(equalTo(asList(expect))));
}

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

@Override
public Task<Void> flush(Actor actor)
{
  final RemoteReference actorReference = (RemoteReference) actor;
  masterCache.asMap().forEach((method, cache) -> {
    cache.invalidate(actorReference);
  });
  return Task.done();
}

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

/**
 * Gets the human friendly location of where the violation was raised.
 */
public static String getMessage(ConstraintViolation<?> v, Invocable invocable) {
  final Pair<Path, ? extends ConstraintDescriptor<?>> of =
      Pair.of(v.getPropertyPath(), v.getConstraintDescriptor());
  final String cachePrefix = PREFIX_CACHE.getIfPresent(of);
  if (cachePrefix == null) {
    final String prefix = calculatePrefix(v, invocable);
    PREFIX_CACHE.put(of, prefix);
    return prefix + v.getMessage();
  }
  return cachePrefix + v.getMessage();
}

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

@Test(dataProvider = "caches")
@CacheSpec(implementation = Implementation.Caffeine, maximumSize = Maximum.FULL,
  weigher = CacheWeigher.COLLECTION, population = Population.EMPTY,
  keys = ReferenceType.STRONG, values = ReferenceType.STRONG)
public void remove(Cache<String, List<Integer>> cache,
  CacheContext context, Eviction<?, ?> eviction) {
 cache.putAll(ImmutableMap.of("a", asList(1, 2, 3), "b", asList(1)));
 assertThat(cache.asMap().remove("a"), is(asList(1, 2, 3)));
 assertThat(cache.estimatedSize(), is(1L));
 assertThat(eviction.weightedSize().getAsLong(), is(1L));
}

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

/** Performs the bulk load where the existing entries are retained. */
private void loadAllAndKeepExisting(Set<? extends K> keys) {
 List<K> keysToLoad = keys.stream()
   .filter(key -> !cache.asMap().containsKey(key))
   .collect(toList());
 Map<K, V> result = cacheLoader.get().loadAll(keysToLoad);
 for (Map.Entry<K, V> entry : result.entrySet()) {
  if ((entry.getKey() != null) && (entry.getValue() != null)) {
   putIfAbsentNoAwait(entry.getKey(), entry.getValue(), /* publishToWriter */ false);
  }
 }
}

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

@Override
public void close(String namespace)
{
 if (config.isEvictOnClose()) {
  cache.asMap().keySet().removeIf(key -> key.namespace.equals(namespace));
 }
}

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

@Test(dataProvider = "caches")
@CacheSpec(population = { Population.PARTIAL, Population.FULL })
public void invalidateAll_partial(Cache<Integer, Integer> cache, CacheContext context) {
 List<Integer> keys = cache.asMap().keySet().stream()
   .filter(i -> ((i % 2) == 0))
   .collect(Collectors.toList());
 cache.invalidateAll(keys);
 assertThat(cache.estimatedSize(), is(context.initialSize() - keys.size()));
 assertThat(cache, hasRemovalNotifications(context, keys.size(), RemovalCause.EXPLICIT));
 verifyWriter(context, (verifier, writer) -> {
  verifier.deletedAll(Maps.filterKeys(context.original(), Predicates.in(keys)), RemovalCause.EXPLICIT);
 });
}

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

@Test(dataProvider = "caches")
@CacheSpec(implementation = Implementation.Caffeine,
  maximumSize = Maximum.FULL, weigher = CacheWeigher.TEN)
public void weightedSize(Cache<Integer, Integer> cache, CacheContext context,
  Eviction<Integer, Integer> eviction) {
 long weightedSize = 0;
 for (Integer key : cache.asMap().keySet()) {
  weightedSize += eviction.weightOf(key).getAsInt();
 }
 assertThat(weightedSize, is(eviction.weightedSize().getAsLong()));
 assertThat(eviction.weightedSize().getAsLong(), is(10 * cache.estimatedSize()));
}

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

@Test(dataProvider = "caches")
@CacheSpec(implementation = Implementation.Caffeine, maximumSize = Maximum.FULL,
  weigher = CacheWeigher.COLLECTION, population = Population.EMPTY,
  keys = ReferenceType.STRONG, values = ReferenceType.STRONG)
public void replace_sameWeight(Cache<String, List<Integer>> cache,
  CacheContext context, Eviction<?, ?> eviction) {
 cache.putAll(ImmutableMap.of("a", asList(1, 2, 3), "b", asList(1)));
 cache.asMap().replace("a", asList(-1, -2, -3));
 assertThat(cache.estimatedSize(), is(2L));
 assertThat(eviction.weightedSize().getAsLong(), is(4L));
}

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

@Test(dataProvider = "caches", expectedExceptions = DeleteException.class)
@CacheSpec(keys = ReferenceType.STRONG, values = {ReferenceType.WEAK, ReferenceType.SOFT},
  implementation = Implementation.Caffeine, expireAfterAccess = Expire.DISABLED,
  expireAfterWrite = Expire.DISABLED, maximumSize = Maximum.DISABLED,
  weigher = CacheWeigher.DEFAULT, population = Population.FULL, stats = Stats.ENABLED,
  compute = Compute.SYNC, removalListener = Listener.CONSUMING, writer = Writer.EXCEPTIONAL)
public void get_writerFails(Cache<Integer, Integer> cache, CacheContext context) {
 Integer key = context.firstKey();
 try {
  context.clear();
  GcFinalization.awaitFullGc();
  cache.get(key, Function.identity());
 } finally {
  context.disableRejectingCacheWriter();
  assertThat(cache.asMap().isEmpty(), is(false));
 }
}

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

@Test(dataProvider = "caches", expectedExceptions = DeleteException.class)
@CacheSpec(keys = ReferenceType.STRONG, values = {ReferenceType.WEAK, ReferenceType.SOFT},
  implementation = Implementation.Caffeine, expireAfterAccess = Expire.DISABLED,
  expireAfterWrite = Expire.DISABLED, maximumSize = Maximum.DISABLED,
  weigher = CacheWeigher.DEFAULT, population = Population.FULL, stats = Stats.ENABLED,
  compute = Compute.SYNC, removalListener = Listener.CONSUMING, writer = Writer.EXCEPTIONAL)
public void invalidate_writerFails(Cache<Integer, Integer> cache, CacheContext context) {
 Integer key = context.firstKey();
 try {
  context.clear();
  GcFinalization.awaitFullGc();
  cache.invalidate(key);
 } finally {
  context.disableRejectingCacheWriter();
  assertThat(cache.asMap().isEmpty(), is(false));
 }
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public void put(Object key, @Nullable Object value) {
  this.cache.put(key, toStoreValue(value));
}

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

@Test(dataProvider = "caches")
@CacheSpec(implementation = Implementation.Caffeine, requiresWeakOrSoft = true,
  expireAfterAccess = Expire.DISABLED, expireAfterWrite = Expire.DISABLED,
  maximumSize = Maximum.UNREACHABLE, weigher = CacheWeigher.COLLECTION,
  population = Population.EMPTY, stats = Stats.ENABLED, removalListener = Listener.DEFAULT,
  writer = Writer.DISABLED)
public void compute_weighted(Cache<Integer, List<Integer>> cache, CacheContext context) {
 Integer key = context.absentKey();
 cache.put(key, ImmutableList.of(1));
 GcFinalization.awaitFullGc();
 cache.asMap().compute(key, (k, v) -> ImmutableList.of(1, 2, 3));
 assertThat(cache.policy().eviction().get().weightedSize().getAsLong(), is(3L));
}

代码示例来源:origin: spring-projects/spring-framework

@Override
@Nullable
protected Object lookup(Object key) {
  return this.cache.getIfPresent(key);
}

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

@CheckNoStats
@Test(dataProvider = "caches", expectedExceptions = WriteException.class)
@CacheSpec(implementation = Implementation.Caffeine, keys = ReferenceType.STRONG,
  compute = Compute.SYNC, writer = Writer.EXCEPTIONAL, removalListener = Listener.REJECTING)
public void put_insert_writerFails(Cache<Integer, Integer> cache, CacheContext context) {
 try {
  cache.put(context.absentKey(), context.absentValue());
 } finally {
  assertThat(cache.asMap(), equalTo(context.original()));
 }
}

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

@Test(dataProvider = "caches")
@CacheSpec(population = Population.EMPTY, expiryTime = Expire.ONE_MINUTE,
  mustExpireWithAnyOf = { AFTER_WRITE, VARIABLE },
  expiry = { CacheExpiry.DISABLED, CacheExpiry.WRITE },
  expireAfterWrite = {Expire.DISABLED, Expire.ONE_MINUTE})
public void get_writeTime(Cache<Integer, Integer> cache, CacheContext context) {
 Integer key = context.absentKey();
 Integer value = context.absentValue();
 cache.get(key, k -> {
  context.ticker().advance(5, TimeUnit.MINUTES);
  return value;
 });
 assertThat(cache.estimatedSize(), is(1L));
 assertThat(cache.getIfPresent(key), is(value));
}

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

@Test(dataProvider = "caches")
@CacheSpec(values = {ReferenceType.WEAK, ReferenceType.SOFT}, population = Population.FULL)
public void identity_values(Cache<Integer, Integer> cache, CacheContext context) {
 @SuppressWarnings("deprecation")
 Integer value = new Integer(context.original().get(context.firstKey()));
 assertThat(cache.asMap().containsValue(value), is(false));
}

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

@Test(dataProvider = "caches")
@CacheSpec(requiresWeakOrSoft = true, expireAfterAccess = Expire.DISABLED,
  expireAfterWrite = Expire.DISABLED, maximumSize = Maximum.DISABLED,
  weigher = CacheWeigher.DEFAULT, population = Population.FULL, stats = Stats.ENABLED,
  removalListener = Listener.CONSUMING)
public void invalidate(Cache<Integer, Integer> cache, CacheContext context) {
 Integer key = context.firstKey();
 Integer value = cache.getIfPresent(key);
 context.clear();
 GcFinalization.awaitFullGc();
 awaitFullCleanup(cache);
 assertThat(cache.estimatedSize(), is(1L));
 cache.invalidate(key);
 assertThat(value, is(notNullValue()));
 assertThat(cache.estimatedSize(), is(0L));
 long count = context.initialSize() - 1;
 assertThat(cache, hasRemovalNotifications(context, count, RemovalCause.COLLECTED));
 verifyWriter(context, (verifier, writer) -> verifier.deletions(count, RemovalCause.COLLECTED));
}

相关文章