教程 > Guava 教程 > Guava 基础 阅读:25

Guava Caching 实用程序

Guava 通过接口 LoadingCache<K,V> 提供了非常强大的基于内存的缓存机制。 值会自动加载到缓存中,它提供了许多可用于缓存需求的实用方法。


接口声明

以下是 com.google.common.cache.LoadingCache<K,V> 接口的声明

@Beta
@GwtCompatible
public interface LoadingCache<K,V>
   extends Cache<K,V>, Function<K,V>

接口方法

序号 方法 说明
1 V apply(K key) 已弃用。 提供满足Function接口; 使用 get(K) 或 getUnchecked(K) 代替。
2 ConcurrentMap<K,V> asMap() 返回存储在此缓存中的条目的视图作为线程安全映射。
3 V get(K key) 返回与此缓存中的键关联的值,如有必要,首先加载该值。
4 ImmutableMap<K,V> getAll(Iterable<? extends K> keys) 返回与键关联的值的映射,必要时创建或检索这些值。
5 V getUnchecked(K key) 返回与此缓存中的键关联的值,如有必要,首先加载该值。
6 void refresh(K key) 为键加载一个新值,可能是异步的。

LoadingCache 示例

C:/> Guava 中使用我们选择的任何编辑器创建以下 java 程序。

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[]) {
   
      //根据员工 ID 为员工创建缓存
      LoadingCache<String, Employee> employeeCache = 
         CacheBuilder.newBuilder()
         .maximumSize(100)                             // 最多可缓存 100 条记录
         .expireAfterAccess(30, TimeUnit.MINUTES)      // 缓存将在访问 30 分钟后过期
         .build(new CacheLoader<String, Employee>() {  // 构建缓存加载器
            
            @Override
            public Employee load(String empId) throws Exception {
               return getFromDatabase(empId);
            } 
         });

      try {            
         //第一次调用时,缓存将填充相应的员工记录
         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.printStackTrace();
      }
   }

   private static Employee getFromDatabase(String empId) {
   
      Employee e1 = new Employee("Mahesh", "Finance", "100");
      Employee e2 = new Employee("Rohan", "IT", "103");
      Employee e3 = new Employee("Sohan", "Admin", "110");

      Map<String, Employee> database = new HashMap<String, Employee>();
      
      database.put("100", e1);
      database.put("103", e2);
      database.put("110", e3);
      
      System.out.println("Database hit for" + empId);
      
      return database.get(empId);        
   }
}

class Employee {
   String name;
   String dept;
   String emplD;

   public Employee(String name, String dept, String empID) {
      this.name = name;
      this.dept = dept;
      this.emplD = empID;
   }
   
   public String getName() {
      return name;
   }
   
   public void setName(String name) {
      this.name = name;
   }
   
   public String getDept() {
      return dept;
   }
   
   public void setDept(String dept) {
      this.dept = dept;
   }
   
   public String getEmplD() {
      return emplD;
   }
   
   public void setEmplD(String emplD) {
      this.emplD = emplD;
   }

   @Override
   public String toString() {
      return MoreObjects.toStringHelper(Employee.class)
      .add("Name", name)
      .add("Department", dept)
      .add("Emp Id", emplD).toString();
   }    
}

验证结果

使用 javac 编译器编译类,如下所示

C:\Guava>javac GuavaTester.java

现在运行 GuavaTester 以查看结果。

C:\Guava>java GuavaTester

结果如下

Invocation #1
Database hit for100
Employee{Name=Mahesh, Department=Finance, Emp Id=100}
Database hit for103
Employee{Name=Rohan, Department=IT, Emp Id=103}
Database hit for110
Employee{Name=Sohan, Department=Admin, Emp Id=110}
Invocation #2
Employee{Name=Mahesh, Department=Finance, Emp Id=100}
Employee{Name=Rohan, Department=IT, Emp Id=103}
Employee{Name=Sohan, Department=Admin, Emp Id=110}

查看笔记

扫码一下
查看教程更方便