本文整理汇总了Java中com.github.benmanes.caffeine.cache.LoadingCache类的典型用法代码示例。如果您正苦于以下问题:Java LoadingCache类的具体用法?Java LoadingCache怎么用?Java LoadingCache使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
LoadingCache类属于com.github.benmanes.caffeine.cache包,在下文中一共展示了LoadingCache类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: loadingCacheExposesMetricsForLoadsAndExceptions
import com.github.benmanes.caffeine.cache.LoadingCache; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Test
void loadingCacheExposesMetricsForLoadsAndExceptions() throws Exception {
LoadingCache<Integer, String> cache = CaffeineCacheMetrics.monitor(registry, Caffeine.newBuilder()
.recordStats()
.build(key -> {
if (key % 2 == 0)
throw new Exception("no evens!");
return key.toString();
}), "c", userTags);
cache.get(1);
cache.get(1);
try {
cache.get(2); // throws exception
} catch (Exception ignored) {
}
cache.get(3);
assertThat(registry.mustFind("c.requests").tags("result", "hit").tags(userTags).functionCounter().count()).isEqualTo(1.0);
assertThat(registry.mustFind("c.requests").tags("result", "miss").tags(userTags).functionCounter().count()).isEqualTo(3.0);
assertThat(registry.mustFind("c.load").tags("result", "failure").functionCounter().count()).isEqualTo(1.0);
assertThat(registry.mustFind("c.load").tags("result", "success").functionCounter().count()).isEqualTo(2.0);
}
示例2: add
import com.github.benmanes.caffeine.cache.LoadingCache; //导入依赖的package包/类
void add(Cache<?, ?> cache, Ticker ticker) {
synchronized (cacheRefs) {
for (CacheReference ref : cacheRefs) {
if (ref.get() == cache) {
// Do not aggregate more than once for the same instance.
return;
}
}
cacheRefs.add(new CacheReference(cache, ticker));
}
if (cache instanceof LoadingCache && hasLoadingCache.compareAndSet(false, true)) {
// Add the following meters only for LoadingCache and only once.
final String loads = idPrefix.name("loads");
parent.more().counter(loads, idPrefix.tags("result", "success"), this,
func(LOAD_SUCCESS_COUNT, ref -> ref.cacheStats.loadSuccessCount()));
parent.more().counter(loads, idPrefix.tags("result", "failure"), this,
func(LOAD_FAILURE_COUNT, ref -> ref.cacheStats.loadFailureCount()));
parent.more().counter(idPrefix.name("loadDuration"), idPrefix.tags(), this,
func(TOTAL_LOAD_TIME, ref -> ref.cacheStats.totalLoadTime()));
}
}
示例3: cacheType
import com.github.benmanes.caffeine.cache.LoadingCache; //导入依赖的package包/类
@SuppressWarnings("rawtypes")
private static List<TypeLiteral> cacheType(final String name, final Object cache,
final Type superclass) {
Class[] ctypes;
if (cache instanceof AsyncLoadingCache) {
ctypes = new Class[]{AsyncLoadingCache.class };
} else if (cache instanceof LoadingCache) {
ctypes = new Class[]{LoadingCache.class, Cache.class };
} else {
ctypes = new Class[]{Cache.class };
}
List<TypeLiteral> result = new ArrayList<>(ctypes.length);
for (Class ctype : ctypes) {
if (name.equals("session")) {
result.add(TypeLiteral.get(Types.newParameterizedType(ctype, String.class, Session.class)));
} else {
result.add(TypeLiteral.get(Types.newParameterizedType(ctype, types(superclass))));
}
}
return result;
}
示例4: execute
import com.github.benmanes.caffeine.cache.LoadingCache; //导入依赖的package包/类
@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Group group, List<String> args, String label) {
if (ArgumentPermissions.checkViewPerms(plugin, sender, getPermission().get(), group)) {
Message.COMMAND_NO_PERMISSION.send(sender);
return CommandResult.NO_PERMISSION;
}
String query = NodeFactory.groupNode(group.getName());
int page = ArgumentUtils.handleIntOrElse(0, args, 1);
Message.SEARCH_SEARCHING_MEMBERS.send(sender, group.getName());
List<HeldPermission<UUID>> matchedUsers = plugin.getStorage().getUsersWithPermission(query).join();
List<HeldPermission<String>> matchedGroups = plugin.getStorage().getGroupsWithPermission(query).join();
int users = matchedUsers.size();
int groups = matchedGroups.size();
Message.SEARCH_RESULT.send(sender, users + groups, users, groups);
if (!matchedUsers.isEmpty()) {
LoadingCache<UUID, String> uuidLookups = Caffeine.newBuilder()
.build(u -> {
String s = plugin.getStorage().getName(u).join();
if (s == null || s.isEmpty() || s.equals("null")) {
s = u.toString();
}
return s;
});
sendResult(sender, matchedUsers, uuidLookups::get, Message.SEARCH_SHOWING_USERS, HolderType.USER, label, page);
}
if (!matchedGroups.isEmpty()) {
sendResult(sender, matchedGroups, Function.identity(), Message.SEARCH_SHOWING_GROUPS, HolderType.GROUP, label, page);
}
return CommandResult.SUCCESS;
}
示例5: execute
import com.github.benmanes.caffeine.cache.LoadingCache; //导入依赖的package包/类
@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, List<String> args, String label) {
String query = args.get(0);
int page = ArgumentUtils.handleIntOrElse(1, args, 1);
Message.SEARCH_SEARCHING.send(sender, query);
List<HeldPermission<UUID>> matchedUsers = plugin.getStorage().getUsersWithPermission(query).join();
List<HeldPermission<String>> matchedGroups = plugin.getStorage().getGroupsWithPermission(query).join();
int users = matchedUsers.size();
int groups = matchedGroups.size();
Message.SEARCH_RESULT.send(sender, users + groups, users, groups);
if (!matchedUsers.isEmpty()) {
LoadingCache<UUID, String> uuidLookups = Caffeine.newBuilder()
.build(u -> {
String s = plugin.getStorage().getName(u).join();
if (s == null || s.isEmpty() || s.equals("null")) {
s = u.toString();
}
return s;
});
sendResult(sender, matchedUsers, uuidLookups::get, Message.SEARCH_SHOWING_USERS, HolderType.USER, label, page);
}
if (!matchedGroups.isEmpty()) {
sendResult(sender, matchedGroups, Function.identity(), Message.SEARCH_SHOWING_GROUPS, HolderType.GROUP, label, page);
}
return CommandResult.SUCCESS;
}
示例6: createCache
import com.github.benmanes.caffeine.cache.LoadingCache; //导入依赖的package包/类
protected LoadingCache<String, IntervalCollection> createCache(final long cacheSize,
final long expire,
final TimeUnit timeUnit) {
this.cacheSize = cacheSize;
this.expire = expire;
this.timeUnit = timeUnit;
return Caffeine.newBuilder()
.maximumSize(cacheSize)
.expireAfterAccess(expire, timeUnit)
.build(super::load);
}
示例7: buildAddressCache
import com.github.benmanes.caffeine.cache.LoadingCache; //导入依赖的package包/类
private LoadingCache<RemoteSource, Set<Context>> buildAddressCache(final String contextKey,
final Function<RemoteSource, InetAddress> function) {
return Caffeine.newBuilder()
.weakKeys()
.build(key -> {
final ImmutableSet.Builder<Context> builder = ImmutableSet.builder();
final InetAddress address = checkNotNull(function.apply(key), "address");
builder.add(new Context(contextKey, address.getHostAddress()));
for (String set : Maps.filterValues(Lantern.getGame().getGlobalConfig().getIpSets(), input -> input.test(address)).keySet()) {
builder.add(new Context(contextKey, set));
}
return builder.build();
});
}
示例8: loadingCacheExposesMetricsForLoadsAndExceptions
import com.github.benmanes.caffeine.cache.LoadingCache; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Test
public void loadingCacheExposesMetricsForLoadsAndExceptions() throws Exception {
CacheLoader<String, String> loader = mock(CacheLoader.class);
when(loader.load(anyString()))
.thenReturn("First User")
.thenThrow(new RuntimeException("Seconds time fails"))
.thenReturn("Third User");
LoadingCache<String, String> cache = Caffeine.newBuilder().recordStats().build(loader);
CollectorRegistry registry = new CollectorRegistry();
CacheMetricsCollector collector = new CacheMetricsCollector().register(registry);
collector.addCache("loadingusers", cache);
cache.get("user1");
cache.get("user1");
try {
cache.get("user2");
} catch (Exception e) {
// ignoring.
}
cache.get("user3");
assertMetric(registry, "caffeine_cache_hit_total", "loadingusers", 1.0);
assertMetric(registry, "caffeine_cache_miss_total", "loadingusers", 3.0);
assertMetric(registry, "caffeine_cache_load_failure_total", "loadingusers", 1.0);
assertMetric(registry, "caffeine_cache_loads_total", "loadingusers", 3.0);
assertMetric(registry, "caffeine_cache_load_duration_seconds_count", "loadingusers", 3.0);
assertMetricGreatThan(registry, "caffeine_cache_load_duration_seconds_sum", "loadingusers", 0.0);
}
示例9: bindTo
import com.github.benmanes.caffeine.cache.LoadingCache; //导入依赖的package包/类
@Override
public void bindTo(MeterRegistry registry) {
Gauge.builder(name + ".estimated.size", cache, Cache::estimatedSize)
.tags(tags)
.description("The approximate number of entries in this cache")
.register(registry);
FunctionCounter.builder(name + ".requests", cache, c -> c.stats().missCount())
.tags(tags).tags("result", "miss")
.description("the number of times cache lookup methods have returned an uncached (newly loaded) value, or null")
.register(registry);
FunctionCounter.builder(name + ".requests", cache, c -> c.stats().hitCount())
.tags(tags).tags("result", "hit")
.description("The number of times cache lookup methods have returned a cached value.")
.register(registry);
FunctionCounter.builder(name + ".evictions", cache, c -> c.stats().evictionCount())
.tags(tags)
.description("cache evictions")
.register(registry);
Gauge.builder(name + ".eviction.weight", cache, c -> c.stats().evictionWeight())
.tags(tags)
.description("The sum of weights of evicted entries. This total does not include manual invalidations.")
.register(registry);
if (cache instanceof LoadingCache) {
// dividing these gives you a measure of load latency
TimeGauge.builder(name + ".load.duration", cache, TimeUnit.NANOSECONDS, c -> c.stats().totalLoadTime())
.tags(tags)
.description("The time the cache has spent loading new values")
.register(registry);
FunctionCounter.builder(name + ".load", cache, c -> c.stats().loadSuccessCount())
.tags(tags)
.tags("result", "success")
.description("The number of times cache lookup methods have successfully loaded a new value")
.register(registry);
FunctionCounter.builder(name + ".load", cache, c -> c.stats().loadFailureCount())
.tags(tags).tags("result", "failure")
.description("The number of times {@link Cache} lookup methods failed to load a new value, either " +
"because no value was found or an exception was thrown while loading")
.register(registry);
}
}
示例10: create
import com.github.benmanes.caffeine.cache.LoadingCache; //导入依赖的package包/类
public Mache<K, V> create(Class<K> keyType, Class<V> valueType, MacheLoader<K, V> cacheLoader) {
LoadingCache<K, V> cache = builder.build(new CacheLoaderAdapter<>(cacheLoader));
return new CaffeineMache<>(cacheLoader, cache);
}
示例11: CaffeineMache
import com.github.benmanes.caffeine.cache.LoadingCache; //导入依赖的package包/类
/**
* @param cacheLoader The MacheLoader of the backing store for this Mache.
* @param cache The created Caffeine LoadingCache.
*/
public CaffeineMache(final MacheLoader<K, V> cacheLoader, LoadingCache<K, V> cache) {
this.cacheLoader = cacheLoader;
this.cache = cache;
cacheId = Generators.nameBasedGenerator().generate(getName() + toString());
}
示例12: RequireLoadingCache
import com.github.benmanes.caffeine.cache.LoadingCache; //导入依赖的package包/类
@Inject
public RequireLoadingCache(final LoadingCache<String, Object> cache) {
requireNonNull(cache, "The cache is required.");
}
示例13: collect
import com.github.benmanes.caffeine.cache.LoadingCache; //导入依赖的package包/类
@Override
public List<MetricFamilySamples> collect() {
List<MetricFamilySamples> mfs = new ArrayList<MetricFamilySamples>();
List<String> labelNames = Arrays.asList("cache");
CounterMetricFamily cacheHitTotal = new CounterMetricFamily("caffeine_cache_hit_total",
"Cache hit totals", labelNames);
mfs.add(cacheHitTotal);
CounterMetricFamily cacheMissTotal = new CounterMetricFamily("caffeine_cache_miss_total",
"Cache miss totals", labelNames);
mfs.add(cacheMissTotal);
CounterMetricFamily cacheRequestsTotal = new CounterMetricFamily("caffeine_cache_requests_total",
"Cache request totals, hits + misses", labelNames);
mfs.add(cacheRequestsTotal);
CounterMetricFamily cacheEvictionTotal = new CounterMetricFamily("caffeine_cache_eviction_total",
"Cache eviction totals, doesn't include manually removed entries", labelNames);
mfs.add(cacheEvictionTotal);
GaugeMetricFamily cacheEvictionWeight = new GaugeMetricFamily("caffeine_cache_eviction_weight",
"Cache eviction weight", labelNames);
mfs.add(cacheEvictionWeight);
CounterMetricFamily cacheLoadFailure = new CounterMetricFamily("caffeine_cache_load_failure_total",
"Cache load failures", labelNames);
mfs.add(cacheLoadFailure);
CounterMetricFamily cacheLoadTotal = new CounterMetricFamily("caffeine_cache_loads_total",
"Cache loads: both success and failures", labelNames);
mfs.add(cacheLoadTotal);
GaugeMetricFamily cacheSize = new GaugeMetricFamily("caffeine_cache_estimated_size",
"Estimated cache size", labelNames);
mfs.add(cacheSize);
SummaryMetricFamily cacheLoadSummary = new SummaryMetricFamily("caffeine_cache_load_duration_seconds",
"Cache load duration: both success and failures", labelNames);
mfs.add(cacheLoadSummary);
for(Map.Entry<String, Cache> c: children.entrySet()) {
List<String> cacheName = Arrays.asList(c.getKey());
CacheStats stats = c.getValue().stats();
try{
cacheEvictionWeight.addMetric(cacheName, stats.evictionWeight());
} catch (Exception e) {
// EvictionWeight metric is unavailable, newer version of Caffeine is needed.
}
cacheHitTotal.addMetric(cacheName, stats.hitCount());
cacheMissTotal.addMetric(cacheName, stats.missCount());
cacheRequestsTotal.addMetric(cacheName, stats.requestCount());
cacheEvictionTotal.addMetric(cacheName, stats.evictionCount());
cacheSize.addMetric(cacheName, c.getValue().estimatedSize());
if(c.getValue() instanceof LoadingCache) {
cacheLoadFailure.addMetric(cacheName, stats.loadFailureCount());
cacheLoadTotal.addMetric(cacheName, stats.loadCount());
cacheLoadSummary.addMetric(cacheName, stats.loadCount(), stats.totalLoadTime() / Collector.NANOSECONDS_PER_SECOND);
}
}
return mfs;
}
示例14: synchronous
import com.github.benmanes.caffeine.cache.LoadingCache; //导入依赖的package包/类
/**
* Returns a view of the entries stored in this cache as a synchronous {@link LoadingCache}.
* A mapping is not present if the value is currently being loaded. Modifications made to the
* synchronous cache directly affect the asynchronous cache. If a modification is made to a
* mapping that is currently loading, the operation blocks until the computation completes.
*
* @return a thread-safe synchronous view of this cache
*/
public LoadingCache<ParsecAsyncHttpRequest, Response> synchronous() {
return asyncLoadingCache.synchronous();
}