Guava通過接口LoadingCache提供了一個(gè)非常強(qiáng)大的基于內(nèi)存的LoadingCache<K,V>。在緩存中自動(dòng)加載值,它提供了許多實(shí)用的方法,在有緩存需求時(shí)非常有用。
以下是forcom.google.common.cache.LoadingCache<K,V>接口的聲明:
@Beta @GwtCompatible public interface LoadingCache<K,V> extends Cache<K,V>, Function<K,V>
S.N. | 方法及說明 |
---|---|
1 |
V apply(K key) 不推薦使用。提供滿足功能接口;使用get(K)或getUnchecked(K)代替。 |
2 |
ConcurrentMap<K,V> asMap() 返回存儲(chǔ)在該緩存作為一個(gè)線程安全的映射條目的視圖。 |
3 |
V get(K key) 返回一個(gè)鍵在這個(gè)高速緩存中,首先裝載如果需要該值相關(guān)聯(lián)的值。 |
4 |
ImmutableMap<K,V> getAll(Iterable<? extends K> keys) 返回一個(gè)鍵相關(guān)聯(lián)的值的映射,創(chuàng)建或必要時(shí)檢索這些值。 |
5 |
V getUnchecked(K key) 返回一個(gè)鍵在這個(gè)高速緩存中,首先裝載如果需要該值相關(guān)聯(lián)的值。 |
6 |
void refresh(K key) 加載鍵key,可能是異步的一個(gè)新值。 |
使用所選擇的編輯器創(chuàng)建下面的java程序 C:/> Guava
GuavaTester.javaimport java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import com.google.common.base.MoreObjects; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; public class GuavaTester { public static void main(String args[]){ //create a cache for employees based on their employee id LoadingCacheemployeeCache = CacheBuilder.newBuilder() .maximumSize(100) // maximum 100 records can be cached .expireAfterAccess(30, TimeUnit.MINUTES) // cache will expire after 30 minutes of access .build(new CacheLoader (){ // build the cacheloader @Override public Employee load(String empId) throws Exception { //make the expensive call return getFromDatabase(empId); } }); try { //on first invocation, cache will be populated with corresponding //employee record System.out.println("Invocation #1"); System.out.println(employeeCache.get("100")); System.out.println(employeeCache.get("103")); System.out.println(employeeCache.get("110")); //second invocation, data will be returned from cache System.out.println("Invocation #2"); System.out.println(employeeCache.get("100")); System.out.println(employeeCache.get("103")); System.out.println(employeeCache.get("110")); } catch (ExecutionException e) { e上一篇:Guava字符串工具下一篇:Guava Throwables類