本文整理汇总了Java中com.google.common.cache.Cache类的典型用法代码示例。如果您正苦于以下问题:Java Cache类的具体用法?Java Cache怎么用?Java Cache使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Cache类属于com.google.common.cache包,在下文中一共展示了Cache类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createInMemoryCache
import com.google.common.cache.Cache; //导入依赖的package包/类
private Cache<Object, Object> createInMemoryCache(String cacheId, String cacheName) {
Cache<Object, Object> inMemoryCache = this.cache.getIfPresent(cacheId);
if (inMemoryCache != null) {
LOG.info("In-memory cache of {}: Size{{}}, {}", cacheId, inMemoryCache.size(), inMemoryCache.stats());
} else {
Integer maxSize = cacheCapSizer.getMaxSize(cacheName);
assert maxSize != null : "Unknown cache.";
LOG.debug("Creating In-memory cache of {}: MaxSize{{}}", cacheId, maxSize);
LoggingEvictionListener evictionListener = new LoggingEvictionListener(cacheId, maxSize);
final CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder().maximumSize(maxSize).recordStats().removalListener(evictionListener);
inMemoryCache = cacheBuilder.build();
evictionListener.setCache(inMemoryCache);
this.cache.put(cacheId, inMemoryCache);
}
return inMemoryCache;
}
示例2: getChronoRange
import com.google.common.cache.Cache; //导入依赖的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;
}
}
示例3: HandlerToPreparePlan
import com.google.common.cache.Cache; //导入依赖的package包/类
public HandlerToPreparePlan(
QueryContext context,
SqlNode sqlNode,
SqlToPlanHandler handler,
Cache<Long, PreparedPlan> planCache,
String sql,
AttemptObserver observer,
SqlHandlerConfig config) {
this.context = context;
this.sqlNode = sqlNode;
this.handler = handler;
this.planCache = planCache;
this.sql = sql;
this.observer = observer;
this.config = config;
}
示例4: getRemoteStatementMap
import com.google.common.cache.Cache; //导入依赖的package包/类
@Override public Cache<Integer, Object>
getRemoteStatementMap(AvaticaConnection connection) throws Exception {
Field metaF = AvaticaConnection.class.getDeclaredField("meta");
metaF.setAccessible(true);
Meta clientMeta = (Meta) metaF.get(connection);
Field remoteMetaServiceF = clientMeta.getClass().getDeclaredField("service");
remoteMetaServiceF.setAccessible(true);
LocalProtobufService remoteMetaService =
(LocalProtobufService) remoteMetaServiceF.get(clientMeta);
// Use the explicitly class to avoid issues with LoggingLocalJsonService
Field remoteMetaServiceServiceF = LocalProtobufService.class.getDeclaredField("service");
remoteMetaServiceServiceF.setAccessible(true);
LocalService remoteMetaServiceService =
(LocalService) remoteMetaServiceServiceF.get(remoteMetaService);
Field remoteMetaServiceServiceMetaF =
remoteMetaServiceService.getClass().getDeclaredField("meta");
remoteMetaServiceServiceMetaF.setAccessible(true);
JdbcMeta serverMeta = (JdbcMeta) remoteMetaServiceServiceMetaF.get(remoteMetaServiceService);
Field jdbcMetaStatementMapF = JdbcMeta.class.getDeclaredField("statementCache");
jdbcMetaStatementMapF.setAccessible(true);
//noinspection unchecked
@SuppressWarnings("unchecked")
Cache<Integer, Object> cache = (Cache<Integer, Object>) jdbcMetaStatementMapF.get(serverMeta);
return cache;
}
示例5: schemaCacheItemsGetAddedUponInstanceAccess
import com.google.common.cache.Cache; //导入依赖的package包/类
public void schemaCacheItemsGetAddedUponInstanceAccess() {
// Initially there should be no entries on the schemaDescriptionIdCache
Cache<SchemaKey, Set<SchemaKey>> schemaDescriptionIdCache = cacheService.getSchemaDescriptionIdCache();
assertEquals(schemaDescriptionIdCache.size(), 0);
// Creating auxiliary objects prior to execute queries
Map<String, Object> variableMap = buildVariableMap(CACHE_TEST_NAMESPACE, MEDIA_DOMAIN_NAME);
SchemaWriteAccess access = buildSchemaWriteAccessCacheTestNamespace();
// Run a query on media that should populate the reference cache for it
GraphQLResult addMediaInstanceResult = instanceService.executeQuery(addMediaInstance, variableMap, access, DEFAULT_MAX_RECURSE_DEPTH);
assertTrue(addMediaInstanceResult.isSuccessful());
// Lookup for "Media" referenced types
Set<SchemaKey> schemaKeySets = schemaDescriptionIdCache.getIfPresent(new SchemaKey(MEDIA_DOMAIN_NAME, SCHEMA_NAME_SPACE));
// Media should have 2 referenced types (Video and Audio)
assertNotNull(schemaKeySets);
assertEquals(schemaKeySets.size(), 2);
assertTrue(schemaKeySets.contains(new SchemaKey(VIDEO_DOMAIN_NAME, SCHEMA_NAME_SPACE)));
assertTrue(schemaKeySets.contains(new SchemaKey(AUDIO_DOMAIN_NAME, SCHEMA_NAME_SPACE)));
}
示例6: getUserState
import com.google.common.cache.Cache; //导入依赖的package包/类
@Override
public OAuthUserState getUserState(String tokenData, HttpServletRequest request)
{
Cache<String, OAuthUserState> userCache = getUserCache(CurrentInstitution.get());
OAuthUserState oauthUserState = userCache.getIfPresent(tokenData);
if( oauthUserState == null )
{
// find the token and the user associated with it
final OAuthToken token = oauthService.getToken(tokenData);
if( token == null )
{
// FIXME: Need to fall back on server language since
// LocaleEncodingFilter has not run yet...
throw new OAuthException(403, OAuthConstants.ERROR_ACCESS_DENIED, languageService
.getResourceBundle(Locale.getDefault(), "resource-centre").getString(KEY_TOKEN_NOT_FOUND));
}
final UserState userState = userService.authenticateAsUser(token.getUsername(),
userService.getWebAuthenticationDetails(request));
oauthUserState = new OAuthUserStateImpl(userState, token);
userCache.put(tokenData, oauthUserState);
}
return (OAuthUserState) oauthUserState.clone();
}
示例7: getValueAndStoreToCache
import com.google.common.cache.Cache; //导入依赖的package包/类
private <T> T getValueAndStoreToCache(String key, Function<String, T> parser, Cache<String, T> cache, T defaultValue) {
long currentConfigVersion = m_configVersion.get();
String value = getProperty(key, null);
if (value != null) {
T result = parser.apply(value);
if (result != null) {
synchronized (this) {
if (m_configVersion.get() == currentConfigVersion) {
cache.put(key, result);
}
}
return result;
}
}
return defaultValue;
}
示例8: Foreman
import com.google.common.cache.Cache; //导入依赖的package包/类
protected Foreman(
final SabotContext context,
final Executor executor,
final CompletionListener listener,
final ExternalId externalId,
final QueryObserver observer,
final UserSession session,
final UserRequest request,
final OptionProvider config,
final ReAttemptHandler attemptHandler,
final CoordToExecTunnelCreator tunnelCreator,
Cache<Long, PreparedPlan> plans) {
this.attemptId = AttemptId.of(externalId);
this.executor = executor;
this.context = context;
this.listener = listener;
this.session = session;
this.request = request;
this.config = config;
this.observer = observer;
this.attemptHandler = attemptHandler;
this.tunnelCreator = tunnelCreator;
this.plans = plans;
}
示例9: getRemoteConnectionMap
import com.google.common.cache.Cache; //导入依赖的package包/类
@Override public Cache<String, Connection>
getRemoteConnectionMap(AvaticaConnection connection) throws Exception {
Field metaF = AvaticaConnection.class.getDeclaredField("meta");
metaF.setAccessible(true);
Meta clientMeta = (Meta) metaF.get(connection);
Field remoteMetaServiceF = clientMeta.getClass().getDeclaredField("service");
remoteMetaServiceF.setAccessible(true);
LocalProtobufService remoteMetaService =
(LocalProtobufService) remoteMetaServiceF.get(clientMeta);
// Get the field explicitly off the correct class to avoid LocalLoggingJsonService.class
Field remoteMetaServiceServiceF = LocalProtobufService.class.getDeclaredField("service");
remoteMetaServiceServiceF.setAccessible(true);
LocalService remoteMetaServiceService =
(LocalService) remoteMetaServiceServiceF.get(remoteMetaService);
Field remoteMetaServiceServiceMetaF =
remoteMetaServiceService.getClass().getDeclaredField("meta");
remoteMetaServiceServiceMetaF.setAccessible(true);
JdbcMeta serverMeta = (JdbcMeta) remoteMetaServiceServiceMetaF.get(remoteMetaServiceService);
Field jdbcMetaConnectionCacheF = JdbcMeta.class.getDeclaredField("connectionCache");
jdbcMetaConnectionCacheF.setAccessible(true);
//noinspection unchecked
@SuppressWarnings("unchecked")
Cache<String, Connection> cache =
(Cache<String, Connection>) jdbcMetaConnectionCacheF.get(serverMeta);
return cache;
}
示例10: fetchDormantChunk
import com.google.common.cache.Cache; //导入依赖的package包/类
public static Chunk fetchDormantChunk(long coords, World world)
{
if (dormantChunkCacheSize == 0) return null; // Don't bother with maps at all if its never gonna get a response
Cache<Long, Chunk> cache = dormantChunkCache.get(world);
if (cache == null)
{
return null;
}
Chunk chunk = cache.getIfPresent(coords);
if (chunk != null)
{
for (ClassInheritanceMultiMap<Entity> eList : chunk.getEntityLists())
{
Iterator<Entity> itr = eList.iterator();
while (itr.hasNext())
{
(itr.next()).resetEntityId();
}
}
}
return chunk;
}
示例11: testStatementLifecycle
import com.google.common.cache.Cache; //导入依赖的package包/类
@Test public void testStatementLifecycle() throws Exception {
ConnectionSpec.getDatabaseLock().lock();
try (AvaticaConnection connection = (AvaticaConnection) getLocalConnection()) {
Map<Integer, AvaticaStatement> clientMap = connection.statementMap;
Cache<Integer, Object> serverMap = getLocalConnectionInternals()
.getRemoteStatementMap(connection);
// Other tests being run might leave statements in the cache.
// The lock guards against more statements being cached during the test.
serverMap.invalidateAll();
assertEquals(0, clientMap.size());
assertEquals(0, serverMap.size());
Statement stmt = connection.createStatement();
assertEquals(1, clientMap.size());
assertEquals(1, serverMap.size());
stmt.close();
assertEquals(0, clientMap.size());
assertEquals(0, serverMap.size());
} finally {
ConnectionSpec.getDatabaseLock().unlock();
}
}
示例12: onRemoval
import com.google.common.cache.Cache; //导入依赖的package包/类
@Override
public void onRemoval(RemovalNotification<Object, Cache<Query, Value>> notification) {
Object key = notification.getKey();
if (key == null) {
return;
}
Cache<Query, Value> valueCache = notification.getValue();
if (valueCache == null) {
return;
}
for (Value value : valueCache.asMap().values()) {
listener.onRemoval(value.shardId, value.bitset);
// if null then this means the shard has already been removed and the stats are 0 anyway for the shard this key belongs to
}
}
示例13: guavaCache
import com.google.common.cache.Cache; //导入依赖的package包/类
@Test
public void guavaCache() throws InterruptedException {
TesTicker ticker = new TesTicker();
Cache<String, Pojo> collection = CacheBuilder.newBuilder().expireAfterAccess(5, TimeUnit.SECONDS).ticker(ticker)
.<String, Pojo> build();
Pojo p1 = new Pojo("p1name", "p1val");
Pojo p2 = new Pojo("p2name", "p2val");
collection.put("p1", p1);
collection.put("p2", p2);
ticker.advance(3, TimeUnit.SECONDS);
Map<String, Pojo> map = collection.asMap();
assertTrue(map.containsKey("p1"));
// map.get("p1");
ticker.advance(3, TimeUnit.SECONDS);
assertEquals(2, collection.size());
assertFalse(map.containsKey("p1"));// 有清除过期操作
assertEquals(1, collection.size());
assertNull(collection.getIfPresent("p2"));
assertNull(collection.getIfPresent("p1"));// 有清除过期操作
assertEquals(0, collection.size());
}
示例14: CommandCreator
import com.google.common.cache.Cache; //导入依赖的package包/类
public CommandCreator(
SabotContext dbContext,
QueryContext context,
CoordToExecTunnelCreator tunnelCreator,
UserRequest request,
AttemptObserver observer,
Cache<Long, PreparedPlan> plans,
Pointer<QueryId> prepareId,
int attemptNumber) {
this.context = context;
this.tunnelCreator = tunnelCreator;
this.request = request;
this.observer = observer;
this.dbContext = dbContext;
this.plans = plans;
this.prepareId = prepareId;
this.attemptNumber = attemptNumber;
}
示例15: get
import com.google.common.cache.Cache; //导入依赖的package包/类
private Schema<?> get(final Class<?> cls, Cache<Class<?>, Schema<?>> cache) {
try {
return cache.get(cls, () -> RuntimeSchema.createFrom(cls));
} catch (ExecutionException e) {
return null;
}
}