下面列出了com.google.common.cache.LoadingCache#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public String apply(String s) {
LoadingCache<Replace, Replacer> cache = REPLACE_CACHE.get();
String replacement = s;
try {
for (Replace replace : replaces) {
Replacer replacer = cache.get(replace);
replacement = replacer.replace(replacement);
if (all) {
continue;
}
if (replacement.equals(s)) {
continue;
}
return replacement;
}
} catch (ExecutionException e) {
throw new RuntimeException("Shouldn't happen", e);
}
return replacement;
}
public static DateTimeZone getDataTimeZone(String collection) {
String timezone = TimeSpec.DEFAULT_TIMEZONE;
try {
DatasetConfigDTO datasetConfig;
LoadingCache<String, DatasetConfigDTO> datasetConfigCache = CACHE_REGISTRY.getDatasetConfigCache();
if (datasetConfigCache != null && datasetConfigCache.get(collection) != null) {
datasetConfig = CACHE_REGISTRY.getDatasetConfigCache().get(collection);
} else {
datasetConfig = DAORegistry.getInstance().getDatasetConfigDAO().findByDataset(collection);
}
if (datasetConfig != null) {
timezone = datasetConfig.getTimezone();
}
} catch (ExecutionException e) {
LOG.error("Exception while getting dataset config for {}", collection);
}
return DateTimeZone.forID(timezone);
}
static
public <K extends PMMLObject, V> V getValue(K key, LoadingCache<K, V> cache){
try {
return cache.get(key);
} catch(ExecutionException | UncheckedExecutionException e){
Throwable cause = e.getCause();
if(cause instanceof PMMLException){
throw (PMMLException)cause;
}
throw new InvalidElementException(key)
.initCause(cause);
}
}
@Test
public void givenCacheLoader_whenGettingItemTwice_shouldOnlyCallOnce() throws ExecutionException {
final LoadingCache<String, String> loadingCache = CacheBuilder.newBuilder()
.build(new CacheLoader<String, String>() {
@Override
public String load(final String s) throws Exception {
return slowMethod(s);
}
});
String value = loadingCache.get("key");
value = loadingCache.get("key");
assertThat(callCount).isEqualTo(1);
assertThat(value).isEqualTo("key");
}
@Test
public void givenCacheLoader_whenRefreshingItem_shouldCallAgain() throws ExecutionException {
final LoadingCache<String, String> loadingCache = CacheBuilder.newBuilder()
.build(new CacheLoader<String, String>() {
@Override
public String load(final String s) throws Exception {
return slowMethod(s);
}
});
String value = loadingCache.get("key");
loadingCache.refresh("key");
assertThat(callCount).isEqualTo(2);
assertThat(value).isEqualTo("key");
}
private static <K, V> V getFromCache(LoadingCache<K, V> cache, K key)
{
V value = cache.getIfPresent(key);
if (value != null) {
return value;
}
try {
return cache.get(key);
}
catch (ExecutionException e) {
throw new PinotException(PinotErrorCode.PINOT_UNCLASSIFIED_ERROR, Optional.empty(), "Cannot fetch from cache " + key, e.getCause());
}
}
/**
* 从指定的loadingCache里获取内容
* @param clazz clazz
* @param key key
* @param <K> key
* @param <V> value
* @return value,没有对应的key或获取异常则返回null
*/
@SuppressWarnings("unchecked")
public <K, V> V get(Class<? extends CacheLoader<K, V>> clazz, K key) {
LoadingCache<K, V> cache = this.loadingCacheMap.get(clazz.getSimpleName());
if (cache != null) {
try {
return cache.get(key);
} catch (Exception e) {
log.error("Get from loadingCache error, {}, {}, {}", clazz, key, e.getMessage(), e);
}
}
return null;
}
public static void main(String[] args) throws ExecutionException {
CacheLoader<String, String> loader = new CacheLoader<String, String>() {
public String load(String key) throws Exception {
Thread.sleep(1000); // 休眠1s,模拟加载数据
System.out.println(key + " is loaded from a cacheLoader!");
return key + "'s value";
}
};
LoadingCache<String, String> loadingCache = CacheBuilder.newBuilder().maximumSize(3).build(loader);// 在构建时指定自动加载器
loadingCache.get("key1");
loadingCache.get("key2");
loadingCache.get("key3");
}
@SuppressWarnings("try")
public Source getSource(final File file) throws ExecutionException {
try (TelemetryUtils.ScopedSpan scope =
TelemetryUtils.startScopedSpan("GlobalCache.getSource")) {
TelemetryUtils.ScopedSpan.addAnnotation(
TelemetryUtils.annotationBuilder().put("file", file.getPath()).build("args"));
final LoadingCache<File, Source> sourceCache = this.getSourceCache();
return sourceCache.get(file);
}
}
/**
* Calculate the relatedness between two articles
*/
public double getRelatedness(Article art1, Article art2, String lang) throws ExecutionException{
comparisonsRequested++;
LoadingCache<ArticlePair, Double> relatednessCache = caches.get(lang);
return relatednessCache.get(new ArticlePair(art1,art2));
}
@Test
public void testCache() throws ExecutionException{
LoadingCache<Long, UserEntity> userCaches = CacheBuilder.newBuilder().expireAfterWrite(2, TimeUnit.SECONDS).maximumSize(400).build(new CacheLoader<Long, UserEntity>(){
@Override
public UserEntity load(Long key) throws Exception {
UserEntity user = new UserEntity();
System.out.println("new user: " + key);
user.setId(key);
return user;
}
});
UserEntity user1 = userCaches.get(1L);
UserEntity user2 = userCaches.get(1L);
Assert.assertNotNull(user1);
Assert.assertNotNull(user2);
Assert.assertTrue(user1==user2);
LangUtils.await(3);
user2 = userCaches.get(1L);
Assert.assertNotNull(user1);
Assert.assertNotNull(user2);
Assert.assertTrue(user1!=user2);
Assert.assertEquals(user1.getId(), user2.getId());
}
private Set<Service> getServices(Credentials creds) throws Exception {
BlobStoreContext tmpContext = BlobStoreContextFactoryImpl.INSTANCE.newBlobStoreContext(location);
try {
tmpContext.getBlobStore().list();
LoadingCache<Credentials, Access> authCache = getAuthCache(tmpContext);
Access tmpAccess = authCache.get(creds);
return ImmutableSet.copyOf(tmpAccess);
} finally {
tmpContext.close();
}
}
/**
* Initializes front-end information from the wave store, if necessary.
* @returns true iff the wave is new = if it doesn't have any wavelet
*/
public boolean initialiseWave(WaveId waveId) throws WaveServerException {
boolean isNew = false;
if(LOG.isFineLoggable()) {
LOG.fine("frontend initialiseWave(" + waveId +")");
}
try {
LoadingCache<WaveletId, PerWavelet> wavelets = perWavelet.getIfPresent(waveId);
if (wavelets == null) {
wavelets = perWavelet.get(waveId);
for (WaveletId waveletId : waveletProvider.getWaveletIds(waveId)) {
ReadableWaveletData wavelet =
waveletProvider.getSnapshot(WaveletName.of(waveId, waveletId)).snapshot;
// Wavelets is a computing map, so get() initializes the entry.
PerWavelet waveletInfo = wavelets.get(waveletId);
synchronized (waveletInfo) {
waveletInfo.currentVersion = wavelet.getHashedVersion();
LOG.info("frontend wavelet " + waveletId + " @" + wavelet.getHashedVersion().getVersion());
if(LOG.isFineLoggable()) {
LOG.fine("frontend wavelet " + waveletId + " @" + wavelet.getHashedVersion().getVersion());
}
waveletInfo.explicitParticipants.addAll(wavelet.getParticipants());
}
}
}
if (wavelets.size() == 0)
isNew = true;
} catch (ExecutionException ex) {
throw new RuntimeException(ex);
}
return isNew;
}
GuidePostsInfo getStats(LoadingCache<GuidePostsKey, GuidePostsInfo> cache, GuidePostsKey guidePostsKey) {
GuidePostsInfo guidePostsInfo;
try {
guidePostsInfo = cache.get(guidePostsKey);
} catch (ExecutionException e) {
assertFalse(true);
return GuidePostsInfo.NO_GUIDEPOST;
}
return guidePostsInfo;
}
@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 = CacheBuilder.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, "guava_cache_hit_total", "loadingusers", 1.0);
assertMetric(registry, "guava_cache_miss_total", "loadingusers", 3.0);
assertMetric(registry, "guava_cache_load_failure_total", "loadingusers", 1.0);
assertMetric(registry, "guava_cache_loads_total", "loadingusers", 3.0);
assertMetric(registry, "guava_cache_load_duration_seconds_count", "loadingusers", 3.0);
assertMetricGreatThan(registry, "guava_cache_load_duration_seconds_sum", "loadingusers", 0.0);
}
/**
* Initializes front-end information from the wave store, if necessary.
*/
public void initialiseWave(WaveId waveId) throws WaveServerException {
if(LOG.isFineLoggable()) {
LOG.fine("frontend initialiseWave(" + waveId +")");
}
try {
if (perWavelet.getIfPresent(waveId) == null) {
LoadingCache<WaveletId, PerWavelet> wavelets = perWavelet.get(waveId);
for (WaveletId waveletId : waveletProvider.getWaveletIds(waveId)) {
ReadableWaveletData wavelet =
waveletProvider.getSnapshot(WaveletName.of(waveId, waveletId)).snapshot;
// Wavelets is a computing map, so get() initializes the entry.
PerWavelet waveletInfo = wavelets.get(waveletId);
synchronized (waveletInfo) {
waveletInfo.currentVersion = wavelet.getHashedVersion();
if(LOG.isFineLoggable()) {
LOG.fine("frontend wavelet " + waveletId + " @" + wavelet.getHashedVersion().getVersion());
}
waveletInfo.explicitParticipants.addAll(wavelet.getParticipants());
}
}
}
} catch (ExecutionException ex) {
throw new RuntimeException(ex);
}
}
@Test
public void testCacheBuilder() throws ExecutionException {
LoadingCache<String, Matcher> cache = CacheBuilder.newBuilder()
.maximumSize(10)
.build(
new CacheLoader<String, Matcher>() {
public Matcher load(String key) {
return Pattern.compile(key).matcher("");
}
});
Matcher m = cache.get(".*");
Matcher m2 = cache.get(".*");
}