Guava – Caching 工具类

来源:这里教程网 时间:2026-02-17 21:41:54 作者:

Guava – Caching 工具类

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

Caching 工具类声明

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

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

Caching 工具类函数

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

LoadingCache 工具类示例

使用你选择的任何编辑器创建以下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<String, Employee> 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<String, Employee>() {  // 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.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();   }    }

Caching 工具类验证结果

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

C:\Guava>javac GuavaTester.java

现在运行GuavaTester来看看结果.

C:\Guava>java GuavaTester

查看结果.

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

相关推荐