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

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

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

Cache.get介绍

[英]Returns the value associated with the key in this cache, obtaining that value from the mappingFunction if necessary. This method provides a simple substitute for the conventional "if cached, return; otherwise create, cache and return" pattern.

If the specified key is not already associated with a value, attempts to compute its value using the given mapping function and enters it into this cache unless null. The entire method invocation is performed atomically, so the function is applied at most once per key. Some attempted update operations on this cache by other threads may be blocked while the computation is in progress, so the computation should be short and simple, and must not attempt to update any other mappings of this cache.

Warning: as with CacheLoader#load, mappingFunction must not attempt to update any other mappings of this cache.
[中]返回与此缓存中的键关联的值,必要时从Mapping函数中获取该值。这个方法提供了一个简单的替代传统的“如果缓存,则返回;否则创建,则缓存并返回”模式。
如果指定的键尚未与值关联,则尝试使用给定的映射函数计算其值,并将其输入此缓存,除非为null。整个方法调用以原子方式执行,因此每个键最多应用一次函数。在计算过程中,其他线程在此缓存上尝试的某些更新操作可能会被阻止,因此计算应该简短,并且不得尝试更新此缓存的任何其他映射。
警告:与CacheLoader#load一样,mappingFunction不得尝试更新此缓存的任何其他映射。

代码示例

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

@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: spring-projects/spring-framework

@SuppressWarnings("unchecked")
@Override
@Nullable
public <T> T get(Object key, final Callable<T> valueLoader) {
  return (T) fromStoreValue(this.cache.get(key, new LoadFunction(valueLoader)));
}

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

public <T> SimpleStreamProxyObject<T> getSubscriber(final SimpleStream streamActorRef)
{
  //noinspection unchecked
  return weakCache.get(streamActorRef, o -> new SimpleStreamProxyObject<T>(this, streamActorRef));
}

代码示例来源:origin: org.springframework/spring-context-support

@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: org.springframework/spring-context-support

@SuppressWarnings("unchecked")
@Override
@Nullable
public <T> T get(Object key, final Callable<T> valueLoader) {
  return (T) fromStoreValue(this.cache.get(key, new LoadFunction(valueLoader)));
}

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

private HttpFile cache(ServiceRequestContext ctx, PathAndEncoding pathAndEncoding, HttpFile file) {
  assert cache != null;
  // TODO(trustin): We assume here that the file being read is small enough that it will not block
  //                an event loop for a long time. Revisit if the assumption turns out to be false.
  final AggregatedHttpFile cachedFile = cache.get(pathAndEncoding, key -> {
    try {
      return file.aggregateWithPooledObjects(MoreExecutors.directExecutor(), ctx.alloc()).get();
    } catch (Exception e) {
      logger.warn("{} Failed to cache a file: {}", ctx, file, Exceptions.peel(e));
      return null;
    }
  });
  return cachedFile != null ? cachedFile : file;
}

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

@CacheSpec
@CheckNoWriter @CheckNoStats
@Test(dataProvider = "caches", expectedExceptions = NullPointerException.class)
public void get_nullKey(Cache<Integer, Integer> cache, CacheContext context) {
 cache.get(null, Function.identity());
}

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

@CacheSpec
@CheckNoWriter @CheckNoStats
@Test(dataProvider = "caches", expectedExceptions = NullPointerException.class)
public void get_nullKeyAndLoader(Cache<Integer, Integer> cache, CacheContext context) {
 cache.get(null, null);
}

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

@CheckNoWriter
@Test(dataProvider = "caches")
@CacheSpec(population = { Population.SINGLETON, Population.PARTIAL, Population.FULL })
public void get_present(Cache<Integer, Integer> cache, CacheContext context) {
 Function<Integer, Integer> loader = key -> { throw new RuntimeException(); };
 assertThat(cache.get(context.firstKey(), loader),
   is(context.original().get(context.firstKey())));
 assertThat(cache.get(context.middleKey(), loader),
   is(context.original().get(context.middleKey())));
 assertThat(cache.get(context.lastKey(), loader),
   is(context.original().get(context.lastKey())));
 assertThat(context, both(hasMissCount(0)).and(hasHitCount(3)));
 assertThat(context, both(hasLoadSuccessCount(0)).and(hasLoadFailureCount(0)));
}

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

@CacheSpec
@CheckNoWriter @CheckNoStats
@Test(dataProvider = "caches", expectedExceptions = NullPointerException.class)
public void get_nullLoader(Cache<Integer, Integer> cache, CacheContext context) {
 cache.get(context.absentKey(), null);
}

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

@CacheSpec(implementation = Implementation.Caffeine,
  population = Population.FULL, expiry = CacheExpiry.MOCKITO)
@Test(dataProvider = "caches", expectedExceptions = ExpirationException.class)
public void get_expiryFails_read(Cache<Integer, Integer> cache, CacheContext context) {
 try {
  context.ticker().advance(1, TimeUnit.HOURS);
  when(context.expiry().expireAfterRead(any(), any(), anyLong(), anyLong()))
    .thenThrow(ExpirationException.class);
  cache.get(context.firstKey(), identity());
 } finally {
  context.ticker().advance(-1, TimeUnit.HOURS);
  assertThat(cache.asMap(), equalTo(context.original()));
 }
}

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

@CacheSpec(implementation = Implementation.Caffeine, population = Population.FULL,
  expiry = CacheExpiry.MOCKITO, writer = Writer.MOCKITO, removalListener = Listener.REJECTING)
@Test(dataProvider = "caches", expectedExceptions = ExpirationException.class)
public void get_expiryFails_create(Cache<Integer, Integer> cache, CacheContext context) {
 try {
  context.ticker().advance(1, TimeUnit.HOURS);
  when(context.expiry().expireAfterCreate(any(), any(), anyLong()))
    .thenThrow(ExpirationException.class);
  cache.get(context.absentKey(), identity());
 } finally {
  context.ticker().advance(-1, TimeUnit.HOURS);
  assertThat(cache.asMap(), equalTo(context.original()));
  verify(context.cacheWriter(), never()).write(anyInt(), anyInt());
 }
}

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

@Test(dataProvider = "caches")
@CacheSpec(mustExpireWithAnyOf = { AFTER_ACCESS, VARIABLE },
  expiry = { CacheExpiry.DISABLED, CacheExpiry.ACCESS }, expiryTime = Expire.ONE_MINUTE,
  expireAfterAccess = Expire.ONE_MINUTE, population = { Population.PARTIAL, Population.FULL })
public void get(Cache<Integer, Integer> cache, CacheContext context) {
 Function<Integer, Integer> mappingFunction = context.original()::get;
 context.ticker().advance(30, TimeUnit.SECONDS);
 cache.get(context.firstKey(), mappingFunction);
 context.ticker().advance(45, TimeUnit.SECONDS);
 cache.get(context.firstKey(), mappingFunction);
 cache.get(context.lastKey(), mappingFunction); // recreated
 cache.cleanUp();
 assertThat(cache.estimatedSize(), is(2L));
 long count = context.initialSize() - 1;
 assertThat(cache, hasRemovalNotifications(context, count, RemovalCause.EXPIRED));
 verifyWriter(context, (verifier, writer) -> verifier.deletions(count, RemovalCause.EXPIRED));
}

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

@Test(dataProvider = "caches")
@CacheSpec(keys = ReferenceType.STRONG, values = {ReferenceType.WEAK, ReferenceType.SOFT},
  expireAfterAccess = Expire.DISABLED, expireAfterWrite = Expire.DISABLED,
  maximumSize = Maximum.DISABLED, weigher = CacheWeigher.DEFAULT,
  population = Population.FULL, stats = Stats.ENABLED, removalListener = Listener.CONSUMING)
public void get(Cache<Integer, Integer> cache, CacheContext context) {
 Integer key = context.firstKey();
 context.clear();
 GcFinalization.awaitFullGc();
 assertThat(cache.get(key, k -> context.absentValue()), is(context.absentValue()));
 long count = context.initialSize() - cache.estimatedSize() + 1;
 if (context.population() != Population.SINGLETON) {
  assertThat(count, is(greaterThan(1L)));
 }
 assertThat(cache, hasRemovalNotifications(context, count, RemovalCause.COLLECTED));
 verifyWriter(context, (verifier, writer) -> verifier.deletions(count, RemovalCause.COLLECTED));
}

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

@CacheSpec
@CheckNoWriter
@Test(dataProvider = "caches")
public void get_absent(Cache<Integer, Integer> cache, CacheContext context) {
 Integer key = context.absentKey();
 Integer value = cache.get(key, k -> context.absentValue());
 assertThat(value, is(context.absentValue()));
 assertThat(context, both(hasMissCount(1)).and(hasHitCount(0)));
 assertThat(context, both(hasLoadSuccessCount(1)).and(hasLoadFailureCount(0)));
}

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

@CacheSpec
@CheckNoWriter
@Test(dataProvider = "caches", expectedExceptions = IllegalStateException.class)
public void get_throwsException(Cache<Integer, Integer> cache, CacheContext context) {
 try {
  cache.get(context.absentKey(), key -> { throw new IllegalStateException(); });
 } finally {
  assertThat(context, both(hasMissCount(1)).and(hasHitCount(0)));
  assertThat(context, both(hasLoadSuccessCount(0)).and(hasLoadFailureCount(1)));
 }
}

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

@Test(dataProvider = "caches")
@CacheSpec(population = { Population.PARTIAL, Population.FULL },
  mustExpireWithAnyOf = { AFTER_WRITE, VARIABLE }, expireAfterWrite = Expire.ONE_MINUTE,
  expiry = { CacheExpiry.DISABLED, CacheExpiry.WRITE }, expiryTime = Expire.ONE_MINUTE)
public void get(Cache<Integer, Integer> cache, CacheContext context) {
 Function<Integer, Integer> mappingFunction = context.original()::get;
 context.ticker().advance(30, TimeUnit.SECONDS);
 cache.get(context.firstKey(), mappingFunction);
 context.ticker().advance(45, TimeUnit.SECONDS);
 cache.get(context.lastKey(), mappingFunction); // recreated
 cache.cleanUp();
 assertThat(cache.estimatedSize(), is(1L));
 long count = context.initialSize();
 assertThat(cache, hasRemovalNotifications(context, count, RemovalCause.EXPIRED));
 verifyWriter(context, (verifier, writer) -> verifier.deletions(count, RemovalCause.EXPIRED));
}

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

@Test(dataProvider = "caches", expectedExceptions = DeleteException.class)
@CacheSpec(implementation = Implementation.Caffeine, keys = ReferenceType.STRONG,
  population = Population.FULL, expiryTime = Expire.ONE_MINUTE,
  mustExpireWithAnyOf = { AFTER_ACCESS, AFTER_WRITE, VARIABLE },
  expiry = { CacheExpiry.DISABLED, CacheExpiry.CREATE, CacheExpiry.WRITE, CacheExpiry.ACCESS },
  expireAfterAccess = {Expire.DISABLED, Expire.ONE_MINUTE},
  expireAfterWrite = {Expire.DISABLED, Expire.ONE_MINUTE},
  compute = Compute.SYNC, writer = Writer.EXCEPTIONAL, removalListener = Listener.REJECTING)
public void get_writerFails(Cache<Integer, Integer> cache, CacheContext context) {
 try {
  context.ticker().advance(1, TimeUnit.HOURS);
  cache.get(context.firstKey(), Function.identity());
 } finally {
  context.disableRejectingCacheWriter();
  context.ticker().advance(-1, TimeUnit.HOURS);
  assertThat(cache.asMap(), equalTo(context.original()));
 }
}

相关文章