本文整理汇总了Java中com.google.common.cache.CacheBuilder类的典型用法代码示例。如果您正苦于以下问题:Java CacheBuilder类的具体用法?Java CacheBuilder怎么用?Java CacheBuilder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CacheBuilder类属于com.google.common.cache包,在下文中一共展示了CacheBuilder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: AccessTokenJob
import com.google.common.cache.CacheBuilder; //导入依赖的package包/类
public AccessTokenJob() {
logger.info("init");
accessTokenCache = CacheBuilder.newBuilder()
// 设置并发级别为200,并发级别是指可以同时写缓存的线程数
.concurrencyLevel(200)
// 设置写缓存后1分钟过期
.expireAfterWrite(90, TimeUnit.MINUTES).initialCapacity(10).maximumSize(100)
// 设置要统计缓存的命中率
.recordStats()
// 设置缓存的移除通知
.removalListener(new RemovalListener<AppIdSecret, String>() {
@Override
public void onRemoval(RemovalNotification<AppIdSecret, String> notification) {
logger.info(notification.getKey() + " was removed, cause by " + notification.getCause());
}
}).build(new CacheLoader<AppIdSecret, String>() {
// build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
@Override
public String load(AppIdSecret appIdSecret) throws Exception {
Token token = CommonUtil.getAccessToken(appIdSecret.getAppId(), appIdSecret.getAppSecret());
return token.getToken();
}
});
}
示例2: KMSAudit
import com.google.common.cache.CacheBuilder; //导入依赖的package包/类
/**
* Create a new KMSAudit.
*
* @param windowMs Duplicate events within the aggregation window are quashed
* to reduce log traffic. A single message for aggregated
* events is printed at the end of the window, along with a
* count of the number of aggregated events.
*/
KMSAudit(long windowMs) {
cache = CacheBuilder.newBuilder()
.expireAfterWrite(windowMs, TimeUnit.MILLISECONDS)
.removalListener(
new RemovalListener<String, AuditEvent>() {
@Override
public void onRemoval(
RemovalNotification<String, AuditEvent> entry) {
AuditEvent event = entry.getValue();
if (event.getAccessCount().get() > 0) {
KMSAudit.this.logEvent(event);
event.getAccessCount().set(0);
KMSAudit.this.cache.put(entry.getKey(), event);
}
}
}).build();
executor = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder()
.setDaemon(true).setNameFormat(KMS_LOGGER_NAME + "_thread").build());
executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
cache.cleanUp();
}
}, windowMs / 10, windowMs / 10, TimeUnit.MILLISECONDS);
}
示例3: getChronoRange
import com.google.common.cache.CacheBuilder; //导入依赖的package包/类
/**
* Create a ChronoRange for the given ChronoSeries and sequence of ChronoGenes.
*
* @param chronoSeries ChronoSeries to create ChronoRange for
* @param genes ChronoGene sequence containing ChronoPattern(s) to use for creating ChronoRange
* @return ChronoRange for given ChronoSeries and ChronoGene sequence
*/
@NotNull
public static ChronoRange getChronoRange(@NotNull ChronoSeries chronoSeries, @NotNull ISeq<ChronoGene> genes) {
ChronoRange range = new ChronoRange(requireNonNull(chronoSeries), requireNonNull(genes));
Cache<ISeq<ChronoPattern>, ChronoRange> cacheChronoRange = cacheMap.get(chronoSeries);
if (cacheChronoRange == null) {
cacheChronoRange = CacheBuilder.newBuilder().build();
cacheMap.put(chronoSeries, cacheChronoRange);
}
ChronoRange cacheRange = cacheChronoRange.getIfPresent(range.chronoPatternSeq);
if (cacheRange != null) {
return cacheRange;
} else {
if (range.validRange) {
range.calculateTimestampRanges();
}
cacheChronoRange.put(range.chronoPatternSeq, range);
return range;
}
}
示例4: KeyProviderCache
import com.google.common.cache.CacheBuilder; //导入依赖的package包/类
public KeyProviderCache(long expiryMs) {
cache = CacheBuilder.newBuilder()
.expireAfterAccess(expiryMs, TimeUnit.MILLISECONDS)
.removalListener(new RemovalListener<URI, KeyProvider>() {
@Override
public void onRemoval(
RemovalNotification<URI, KeyProvider> notification) {
try {
notification.getValue().close();
} catch (Throwable e) {
LOG.error(
"Error closing KeyProvider with uri ["
+ notification.getKey() + "]", e);
;
}
}
})
.build();
}
示例5: DFSClientCache
import com.google.common.cache.CacheBuilder; //导入依赖的package包/类
DFSClientCache(NfsConfiguration config, int clientCache) {
this.config = config;
this.clientCache = CacheBuilder.newBuilder()
.maximumSize(clientCache)
.removalListener(clientRemovalListener())
.build(clientLoader());
this.inputstreamCache = CacheBuilder.newBuilder()
.maximumSize(DEFAULT_DFS_INPUTSTREAM_CACHE_SIZE)
.expireAfterAccess(DEFAULT_DFS_INPUTSTREAM_CACHE_TTL, TimeUnit.SECONDS)
.removalListener(inputStreamRemovalListener())
.build(inputStreamLoader());
ShutdownHookManager.get().addShutdownHook(new CacheFinalizer(),
SHUTDOWN_HOOK_PRIORITY);
}
示例6: casEventRepository
import com.google.common.cache.CacheBuilder; //导入依赖的package包/类
@Bean
public CasEventRepository casEventRepository() {
final LoadingCache<String, CasEvent> storage = CacheBuilder.newBuilder()
.initialCapacity(INITIAL_CACHE_SIZE)
.maximumSize(MAX_CACHE_SIZE)
.recordStats()
.expireAfterWrite(EXPIRATION_TIME, TimeUnit.HOURS)
.build(new CacheLoader<String, CasEvent>() {
@Override
public CasEvent load(final String s) throws Exception {
LOGGER.error("Load operation of the cache is not supported.");
return null;
}
});
LOGGER.debug("Created an in-memory event repository to store CAS events for [{}] hours", EXPIRATION_TIME);
return new InMemoryCasEventRepository(storage);
}
示例7: initialize
import com.google.common.cache.CacheBuilder; //导入依赖的package包/类
@PostConstruct
public void initialize() {
AppConfiguration.Cache config = AppConfiguration.CONFIG.getCache();
cache = CacheBuilder.newBuilder()
.maximumSize(config.getMaxSize())
.expireAfterWrite(config.getLifeTime(), TimeUnit.MINUTES)
.recordStats() // This is costly! But we need it because of getCacheStatus().
.build();
// https://github.com/google/guava/wiki/CachesExplained#when-does-cleanup-happen
//
// If we do not clean-up expired objects ourselves, the insertion of objects seems to get slower when
// the size approaches the limit. This is because small clean-ups happen which block the operation.
//
scheduler.scheduleAtFixedRate(
this::cleanUpCache,
config.getCleanUpInterval(),
config.getCleanUpInterval(),
TimeUnit.MINUTES
);
}
示例8: init
import com.google.common.cache.CacheBuilder; //导入依赖的package包/类
public static void init() {
ExampleMod.logger.info("ATTEMPTING TO COMMIT GREAT EVIL:");
try {
doImmenseEvil();
} catch(Throwable e) {
e.printStackTrace();
}
MinecraftForge.EVENT_BUS.register(new Listener());
grassCache = CacheBuilder.newBuilder()
.maximumSize(2048)
.build(
new CacheLoader<GrassCacheKey, Biome>() {
@Override
public Biome load(GrassCacheKey key) {
return DimensionManager.getWorld(key.dim).getBiome(new BlockPos(key.x, 63, key.z));
}
}
);
}
示例9: CachedScriptClassInstancePovider
import com.google.common.cache.CacheBuilder; //导入依赖的package包/类
public CachedScriptClassInstancePovider(Engine engine, Function<String, S> createScriptFunction, String format,
BiFunction<S, Class<T>, T> createInstanceFunction) {
this.createScriptFunction = createScriptFunction;
this.format = format;
this.createInstanceFunction = createInstanceFunction;
long cacheExpireTime = engine.getDefaultParameters().getScriptClassInstancePoviderCacheExpireTime();
if (cacheExpireTime >= 0) {
// Turn on the cache.
CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
if (cacheExpireTime > 0) {
builder.expireAfterAccess(cacheExpireTime, TimeUnit.MILLISECONDS);
}
cache = builder.build(new CacheLoader<String, S>() {
@Override
public S load(String className) throws Exception {
return createScript(className);
}
});
}
}
示例10: BakedWrapper
import com.google.common.cache.CacheBuilder; //导入依赖的package包/类
public BakedWrapper(final Node<?> node, final IModelState state, final boolean smooth, final boolean gui3d, final VertexFormat format, final ImmutableSet<String> meshes, final ImmutableMap<String, TextureAtlasSprite> textures)
{
this(node, state, smooth, gui3d, format, meshes, textures, CacheBuilder.newBuilder()
.maximumSize(128)
.expireAfterAccess(2, TimeUnit.MINUTES)
.<Integer, B3DState>build(new CacheLoader<Integer, B3DState>()
{
public B3DState load(Integer frame) throws Exception
{
IModelState parent = state;
Animation newAnimation = node.getAnimation();
if(parent instanceof B3DState)
{
B3DState ps = (B3DState)parent;
parent = ps.getParent();
}
return new B3DState(newAnimation, frame, frame, 0, parent);
}
}));
}
示例11: CachingReEncryptionKeyProvider
import com.google.common.cache.CacheBuilder; //导入依赖的package包/类
public CachingReEncryptionKeyProvider(AbstractReEncryptionKeyProvider prov, long keyTimeoutMillis,
long eekTimeoutMillis) {
super(prov.getConf());
this.provider = prov;
reEncryptionKeyCache =
CacheBuilder.newBuilder().expireAfterAccess(keyTimeoutMillis,
TimeUnit.MILLISECONDS)
.build(new CacheLoader<ReEncryptionKeyCacheKey, ReEncryptionKeyInstance>() {
@Override
public ReEncryptionKeyInstance load(ReEncryptionKeyCacheKey key) throws Exception {
ReEncryptionKeyInstance kv = provider.createReEncryptionKey(
key.getSrcKeyName(), key.getDstKeyName());
if (kv == null) {
throw new KeyNotFoundException();
}
return kv;
}
});
transformedEEKCache =
CacheBuilder.newBuilder().expireAfterAccess(eekTimeoutMillis,
TimeUnit.MILLISECONDS)
.build();
}
示例12: RENAudit
import com.google.common.cache.CacheBuilder; //导入依赖的package包/类
/**
* Create a new KMSAudit.
*
* @param windowMs Duplicate events within the aggregation window are quashed
* to reduce log traffic. A single message for aggregated
* events is printed at the end of the window, along with a
* count of the number of aggregated events.
*/
RENAudit(long windowMs) {
cache = CacheBuilder.newBuilder()
.expireAfterWrite(windowMs, TimeUnit.MILLISECONDS)
.removalListener(
new RemovalListener<String, AuditEvent>() {
@Override
public void onRemoval(
RemovalNotification<String, AuditEvent> entry) {
AuditEvent event = entry.getValue();
if (event.getAccessCount().get() > 0) {
RENAudit.this.logEvent(event);
event.getAccessCount().set(0);
RENAudit.this.cache.put(entry.getKey(), event);
}
}
}).build();
executor = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder()
.setDaemon(true).setNameFormat(REN_LOGGER_NAME + "_thread").build());
executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
cache.cleanUp();
}
}, windowMs / 10, windowMs / 10, TimeUnit.MILLISECONDS);
}
示例13: RegionReplicaSinkWriter
import com.google.common.cache.CacheBuilder; //导入依赖的package包/类
public RegionReplicaSinkWriter(RegionReplicaOutputSink sink, ClusterConnection connection,
ExecutorService pool, int operationTimeout) {
this.sink = sink;
this.connection = connection;
this.operationTimeout = operationTimeout;
this.rpcRetryingCallerFactory
= RpcRetryingCallerFactory.instantiate(connection.getConfiguration());
this.rpcControllerFactory = RpcControllerFactory.instantiate(connection.getConfiguration());
this.pool = pool;
int nonExistentTableCacheExpiryMs = connection.getConfiguration()
.getInt("hbase.region.replica.replication.cache.disabledAndDroppedTables.expiryMs", 5000);
// A cache for non existing tables that have a default expiry of 5 sec. This means that if the
// table is created again with the same name, we might miss to replicate for that amount of
// time. But this cache prevents overloading meta requests for every edit from a deleted file.
disabledAndDroppedTables = CacheBuilder.newBuilder()
.expireAfterWrite(nonExistentTableCacheExpiryMs, TimeUnit.MILLISECONDS)
.initialCapacity(10)
.maximumSize(1000)
.build();
}
示例14: StaticDatabaseMappingService
import com.google.common.cache.CacheBuilder; //导入依赖的package包/类
public StaticDatabaseMappingService(
MetaStoreMappingFactory metaStoreMappingFactory,
List<AbstractMetaStore> initialMetastores) {
this.metaStoreMappingFactory = metaStoreMappingFactory;
primaryDatabasesCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).maximumSize(1).build(
new CacheLoader<String, List<String>>() {
@Override
public List<String> load(String key) throws Exception {
if (primaryDatabaseMapping != null) {
return primaryDatabaseMapping.getClient().get_all_databases();
} else {
return Lists.newArrayList();
}
}
});
init(initialMetastores);
}
示例15: AtomixLeaderElector
import com.google.common.cache.CacheBuilder; //导入依赖的package包/类
public AtomixLeaderElector(CopycatClient client, Properties properties) {
super(client, properties);
cache = CacheBuilder.newBuilder()
.maximumSize(1000)
.build(CacheLoader.from(topic -> this.client.submit(new GetLeadership(topic))));
cacheUpdater = change -> {
Leadership leadership = change.newValue();
cache.put(leadership.topic(), CompletableFuture.completedFuture(leadership));
};
statusListener = status -> {
if (status == Status.SUSPENDED || status == Status.INACTIVE) {
cache.invalidateAll();
}
};
addStatusChangeListener(statusListener);
}