鍍金池/ 教程/ Java/ Guava緩存工具
Guava原語工具
Guava集合工具
Guava Chars類
Guava Shorts類
Guava CharMatcher類
Guava BigIntegerMath類
Guava Range類
Guava Bimap接口
Guava緩存工具
Guava Longs類
Guava Multiset接口
Guava Table接口
Guava Optional類
Guava LongMath類
Guava Spiltter類
Guava Preconditions類
Guava數(shù)學(xué)工具
Guava Ints類
Guava Ordering類
Guava Throwables類
Guava字符串工具
Guava Objects類
Guava Booleans類
Guava教程
Guava Bytes類
Guava CaseFormat類
Guava環(huán)境設(shè)置
Guava Doubles類
Guava Joiner類
Guava Multimap類
Guava Floats類
Guava IntMath類

Guava緩存工具

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è)新值。

LoadingCache 示例

使用所選擇的編輯器創(chuàng)建下面的java程序 C:/> Guava

GuavaTester.java
import 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
      LoadingCache employeeCache = 
         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類