下面列出了com.google.common.cache.Cache#put ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void register(ConfigMeta meta, String ip, long version) {
Cache<String, Long> cache = onlineClients.get(meta);
if (cache== null) {
Cache<String, Long> newCache = CacheBuilder
.newBuilder()
.expireAfterWrite(timeout, TimeUnit.MILLISECONDS)
.build();
cache = onlineClients.putIfAbsent(meta, newCache);
if (cache == null) {
cache = newCache;
}
}
cache.put(ip, version);
}
/**
* @param args
*/
public static void main(String[] args) {
Cache<String, String> makeMap = CacheBuilder.newBuilder().weakKeys().maximumSize(10).build();
for (int i = 0; i < 7; i++) {
makeMap.put("a" + i, "V" + i);
}
System.out.println(Joiner.on(", ").withKeyValueSeparator("=").join(makeMap.asMap()));
for (int i = 0; i < 1; i++) {
makeMap.put("b" + i, "V" + i);
}
System.out.println(Joiner.on(", ").withKeyValueSeparator("=").join(makeMap.asMap()));
System.out.println(makeMap.asMap().containsKey("a1"));
System.out.println(makeMap.asMap().containsKey("a4"));
System.out.println(makeMap.asMap().containsKey("a5"));
System.out.println(makeMap.asMap().get("a1"));
System.out.println(makeMap.asMap().get("a4"));
System.out.println(makeMap.asMap().get("a5"));
}
public static void main(String[] args) throws InterruptedException {
Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(3).recordStats() // 开启统计信息开关
.build();
cache.put("key1", "value1");
cache.put("key2", "value2");
cache.put("key3", "value3");
cache.put("key4", "value4");
cache.getIfPresent("key1");
cache.getIfPresent("key2");
cache.getIfPresent("key3");
cache.getIfPresent("key4");
cache.getIfPresent("key5");
cache.getIfPresent("key6");
System.out.println(cache.stats()); // 获取统计信息
}
public static void main(String[] args) throws InterruptedException {
RemovalListener<String, String> listener = new RemovalListener<String, String>() {
public void onRemoval(RemovalNotification<String, String> notification) {
System.out.println("[" + notification.getKey() + ":" + notification.getValue() + "] is removed!");
}
};
Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(3).removalListener(listener).build();
Object value = new Object();
cache.put("key1", "value1");
cache.put("key2", "value2");
cache.put("key3", "value3");
cache.put("key4", "value3");
cache.put("key5", "value3");
cache.put("key6", "value3");
cache.put("key7", "value3");
cache.put("key8", "value3");
}
@Override
public List<String> process(){
TextIndex textIndex = getTextIndex();
FieldValue value = getValue();
Cache<FieldValue, List<String>> termTokenCache = CacheUtil.getValue(textIndex, TextUtil.termTokenCaches, TextUtil.termTokenCacheLoader);
List<String> tokens = termTokenCache.getIfPresent(value);
if(tokens == null){
String string = value.asString();
tokens = TextUtil.tokenize(textIndex, string);
termTokenCache.put(value, tokens);
}
return tokens;
}
private <K, V> V loadValue(Cache<K, V> cache, K key, Supplier<V> valueSupplier)
{
if (replay) {
return Optional.ofNullable(cache.getIfPresent(key))
.orElseThrow(() -> new PrestoException(NOT_FOUND, "Missing entry found for key: " + key));
}
V value = valueSupplier.get();
cache.put(key, value);
return value;
}
private <K, V> Response<V> getResponse(Key<K> key, Cache<Key<K>, Response<V>> cache, Factory<Response<V>> responseFactory, Transformer<Key<K>, ? super Response<V>> keyGenerator) {
Response<V> response = key == null ? null : cache.getIfPresent(key);
if (response != null) {
return response;
} else {
response = responseFactory.create();
if (!response.isError()) {
Key<K> actualKey = keyGenerator.transform(response);
cache.put(actualKey, response);
}
return response;
}
}
public void onError(EVCacheEvent e, Throwable t) {
if(!enableThrottleHotKeys.get()) return;
final String appName = e.getAppName();
final Cache<String, Integer> cache = getCache(appName);
if(cache == null) return;
for(EVCacheKey evcKey : e.getEVCacheKeys()) {
final String key = evcKey.getKey();
Integer val = cache.getIfPresent(key);
if(val != null) {
cache.put(key, Integer.valueOf(val.intValue() - 1));
}
}
}
public static CachedGridEntry getOrCreateEntry(World world, int gridX, int gridZ, int primerChunkX, int primerChunkZ) {
Cache<Long, CachedGridEntry> currentValue = gridEntryCache.get(world);
if (currentValue == null) {
currentValue = createGridCache();
gridEntryCache.put(world, currentValue);
}
Long gridEntryKey = (long) gridX << 32 | gridZ & 0xFFFFFFFFL;
CachedGridEntry gridEntry = currentValue.getIfPresent(gridEntryKey);
if (gridEntry == null) {
gridEntry = new CachedGridEntry(world, gridX, gridZ, primerChunkX, primerChunkZ);
currentValue.put(gridEntryKey, gridEntry);
}
return gridEntry;
}
@Test
public void testHandleMessage() throws Exception {
String someWatchKey = "someWatchKey";
String anotherWatchKey = "anotherWatchKey";
String someCacheKey = "someCacheKey";
String anotherCacheKey = "anotherCacheKey";
String someValue = "someValue";
ReleaseMessage someReleaseMessage = mock(ReleaseMessage.class);
when(someReleaseMessage.getMessage()).thenReturn(someWatchKey);
Cache<String, String> cache =
(Cache<String, String>) ReflectionTestUtils.getField(configFileController, "localCache");
cache.put(someCacheKey, someValue);
cache.put(anotherCacheKey, someValue);
watchedKeys2CacheKey.putAll(someWatchKey, Lists.newArrayList(someCacheKey, anotherCacheKey));
watchedKeys2CacheKey.putAll(anotherWatchKey, Lists.newArrayList(someCacheKey, anotherCacheKey));
cacheKey2WatchedKeys.putAll(someCacheKey, Lists.newArrayList(someWatchKey, anotherWatchKey));
cacheKey2WatchedKeys.putAll(anotherCacheKey, Lists.newArrayList(someWatchKey, anotherWatchKey));
configFileController.handleMessage(someReleaseMessage, Topics.APOLLO_RELEASE_TOPIC);
assertTrue(watchedKeys2CacheKey.isEmpty());
assertTrue(cacheKey2WatchedKeys.isEmpty());
}
@Test
public void testScopedCaching() {
KeySpace keySpace = new KeySpace(
new KeySpaceDirectory("path1", KeyType.STRING, "path1"),
new KeySpaceDirectory("path2", KeyType.STRING, "path2")
);
try (FDBRecordContext context = database.openContext()) {
final ResolvedKeySpacePath path1 = keySpace.resolveFromKey(context, Tuple.from("path1"));
final LocatableResolver resolver1 = scopedDirectoryGenerator.apply(database, path1);
Cache<ScopedValue<String>, Long> cache = CacheBuilder.newBuilder().build();
cache.put(resolver1.wrap("stuff"), 1L);
assertThat("values can be read from the cache by scoped string",
cache.getIfPresent(resolver1.wrap("stuff")), is(1L));
assertThat("cache misses when looking for unknown name in scope",
cache.getIfPresent(resolver1.wrap("missing")), equalTo(null));
final ResolvedKeySpacePath path2 = keySpace.resolveFromKey(context, Tuple.from("path2"));
final LocatableResolver resolver2 = scopedDirectoryGenerator.apply(database, path2);
assertThat("cache misses when string is not in this scope",
cache.getIfPresent(resolver2.wrap("stuff")), equalTo(null));
final LocatableResolver newResolver = scopedDirectoryGenerator.apply(database, path1);
assertThat("scoping is determined by value of scope directory, not a reference to it",
cache.getIfPresent(newResolver.wrap("stuff")), is(1L));
}
}
private PTable buildTable(byte[] key, ImmutableBytesPtr cacheKey, HRegion region,
long clientTimeStamp) throws IOException, SQLException {
Scan scan = MetaDataUtil.newTableRowsScan(key, MIN_TABLE_TIMESTAMP, clientTimeStamp);
RegionScanner scanner = region.getScanner(scan);
Cache<ImmutableBytesPtr,PTable> metaDataCache = GlobalCache.getInstance(this.env).getMetaDataCache();
try {
PTable oldTable = metaDataCache.getIfPresent(cacheKey);
long tableTimeStamp = oldTable == null ? MIN_TABLE_TIMESTAMP-1 : oldTable.getTimeStamp();
PTable newTable;
newTable = getTable(scanner, clientTimeStamp, tableTimeStamp);
if (newTable == null) {
return null;
}
if (oldTable == null || tableTimeStamp < newTable.getTimeStamp()) {
if (logger.isDebugEnabled()) {
logger.debug("Caching table "
+ Bytes.toStringBinary(cacheKey.get(), cacheKey.getOffset(),
cacheKey.getLength()) + " at seqNum "
+ newTable.getSequenceNumber() + " with newer timestamp "
+ newTable.getTimeStamp() + " versus " + tableTimeStamp);
}
metaDataCache.put(cacheKey, newTable);
}
return newTable;
} finally {
scanner.close();
}
}
private static void test1() throws InterruptedException {
Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(2).expireAfterWrite(300, TimeUnit.SECONDS)
.build();
cache.put("key1", "value1");
int time = 1;
while (true) {
System.out.println("第" + time++ + "次取到key1的值为:" + cache.getIfPresent("key1"));
Thread.sleep(1000);
}
}
public static void main(String[] args) throws InterruptedException {
Cache<String, Object> cache = CacheBuilder.newBuilder().maximumSize(2).weakValues().build();
Object value = new Object();
cache.put("key1", value);
value = new Object();// 原对象不再有强引用
System.gc();
System.out.println(cache.getIfPresent("key1"));
}
public static void main(String[] args) {
Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(2).build();
cache.put("key1", "value1");
cache.put("key2", "value2");
cache.put("key3", "value3");
System.out.println("第一个值:" + cache.getIfPresent("key1"));
System.out.println("第二个值:" + cache.getIfPresent("key2"));
System.out.println("第三个值:" + cache.getIfPresent("key3"));
}
public static void main(String[] args) {
Cache<String,String> cache = CacheBuilder.newBuilder().build();
cache.put("word","Hello Guava Cache");
System.out.println(cache.getIfPresent("word"));
Object xx=cache.getIfPresent("xx");
System.out.println(xx);
}
public void onComplete(EVCacheEvent e) {
if(!enableThrottleHotKeys.get()) return;
final String appName = e.getAppName();
final Cache<String, Integer> cache = getCache(appName);
if(cache == null) return;
for(EVCacheKey evcKey : e.getEVCacheKeys()) {
final String key = evcKey.getKey();
Integer val = cache.getIfPresent(key);
if(val != null) {
cache.put(key, Integer.valueOf(val.intValue() - 1));
}
}
}
/**
* Returns whether {@code str} matches the glob pattern {@code pattern}. This method may use the
* {@code patternCache} to speed up the matching process.
*
* @param pattern a glob pattern
* @param str the string to match
* @param patternCache a cache from patterns to compiled Pattern objects, or {@code null} to skip
* caching
*/
private static boolean matches(String pattern, String str, Cache<String, Pattern> patternCache) {
if (pattern.length() == 0 || str.length() == 0) {
return false;
}
// Common case: **
if (pattern.equals("**")) {
return true;
}
// Common case: *
if (pattern.equals("*")) {
return true;
}
// If a filename starts with '.', this char must be matched explicitly.
if (str.charAt(0) == '.' && pattern.charAt(0) != '.') {
return false;
}
// Common case: *.xyz
if (pattern.charAt(0) == '*' && pattern.lastIndexOf('*') == 0) {
return str.endsWith(pattern.substring(1));
}
// Common case: xyz*
int lastIndex = pattern.length() - 1;
// The first clause of this if statement is unnecessary, but is an
// optimization--charAt runs faster than indexOf.
if (pattern.charAt(lastIndex) == '*' && pattern.indexOf('*') == lastIndex) {
return str.startsWith(pattern.substring(0, lastIndex));
}
Pattern regex = patternCache == null ? null : patternCache.getIfPresent(pattern);
if (regex == null) {
regex = makePatternFromWildcard(pattern);
if (patternCache != null) {
patternCache.put(pattern, regex);
}
}
return regex.matcher(str).matches();
}
@Override
public void dropTable(RpcController controller, DropTableRequest request,
RpcCallback<MetaDataResponse> done) {
MetaDataResponse.Builder builder = MetaDataResponse.newBuilder();
boolean isCascade = request.getCascade();
byte[][] rowKeyMetaData = new byte[3][];
String tableType = request.getTableType();
byte[] schemaName = null;
byte[] tableName = null;
try {
List<Mutation> tableMetadata = ProtobufUtil.getMutations(request);
MetaDataUtil.getTenantIdAndSchemaAndTableName(tableMetadata, rowKeyMetaData);
byte[] tenantIdBytes = rowKeyMetaData[PhoenixDatabaseMetaData.TENANT_ID_INDEX];
schemaName = rowKeyMetaData[PhoenixDatabaseMetaData.SCHEMA_NAME_INDEX];
tableName = rowKeyMetaData[PhoenixDatabaseMetaData.TABLE_NAME_INDEX];
// Disallow deletion of a system table
if (tableType.equals(PTableType.SYSTEM.getSerializedValue())) {
builder.setReturnCode(MetaDataProtos.MutationCode.UNALLOWED_TABLE_MUTATION);
builder.setMutationTime(EnvironmentEdgeManager.currentTimeMillis());
done.run(builder.build());
return;
}
List<byte[]> tableNamesToDelete = Lists.newArrayList();
byte[] parentTableName = MetaDataUtil.getParentTableName(tableMetadata);
byte[] lockTableName = parentTableName == null ? tableName : parentTableName;
byte[] lockKey = SchemaUtil.getTableKey(tenantIdBytes, schemaName, lockTableName);
byte[] key =
parentTableName == null ? lockKey : SchemaUtil.getTableKey(tenantIdBytes,
schemaName, tableName);
HRegion region = env.getRegion();
MetaDataMutationResult result = checkTableKeyInRegion(key, region);
if (result != null) {
done.run(MetaDataMutationResult.toProto(result));
return;
}
List<RowLock> locks = Lists.newArrayList();
try {
acquireLock(region, lockKey, locks);
if (key != lockKey) {
acquireLock(region, key, locks);
}
List<ImmutableBytesPtr> invalidateList = new ArrayList<ImmutableBytesPtr>();
result =
doDropTable(key, tenantIdBytes, schemaName, tableName, parentTableName,
PTableType.fromSerializedValue(tableType), tableMetadata,
invalidateList, locks, tableNamesToDelete, isCascade);
if (result.getMutationCode() != MutationCode.TABLE_ALREADY_EXISTS) {
done.run(MetaDataMutationResult.toProto(result));
return;
}
Cache<ImmutableBytesPtr,PTable> metaDataCache = GlobalCache.getInstance(this.env).getMetaDataCache();
// Commit the list of deletion.
region.mutateRowsWithLocks(tableMetadata, Collections.<byte[]> emptySet());
long currentTime = MetaDataUtil.getClientTimeStamp(tableMetadata);
for (ImmutableBytesPtr ckey : invalidateList) {
metaDataCache.put(ckey, newDeletedTableMarker(currentTime));
}
if (parentTableName != null) {
ImmutableBytesPtr parentCacheKey = new ImmutableBytesPtr(lockKey);
metaDataCache.invalidate(parentCacheKey);
}
done.run(MetaDataMutationResult.toProto(result));
return;
} finally {
region.releaseRowLocks(locks);
}
} catch (Throwable t) {
logger.error("dropTable failed", t);
ProtobufUtil.setControllerException(controller,
ServerUtil.createIOException(SchemaUtil.getTableName(schemaName, tableName), t));
}
}
@Override
public void put(String cacheName, String key, Object value) {
Cache<String, Object> cache = getCache(cacheName);
cache.put(key, value);
}