开源项目

知识点

相关文章

更多

最近更新

更多

Guava cache缓存工具类

2019-04-23 23:24|来源: 网路

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

接口声明

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

@Beta@GwtCompatiblepublic 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()
返回存储在该缓存作为一个线程安全的映射条目的视图。
3 V get(K key)
返回一个键在这个高速缓存中,首先装载如果需要该值相关联的值。
4 ImmutableMap<K,V> getAll(Iterable<? extends K> keys)
返回一个键相关联的值的映射,创建或必要时检索这些值。
5 V getUnchecked(K key)
返回一个键在这个高速缓存中,首先装载如果需要该值相关联的值。
6 void 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 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.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 database = new HashMap();
      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}


相关问答

更多
  • 只需从构建器中删除expireAfterWrite (它的可选功能): cache = CacheBuilder.newBuilder() .maximumSize(100) .build(....); 这样只有达到maximumSize时才会逐出条目。 Guava的缓存有很好的文档,但您也应该阅读Wiki页面 。 PS如果用“永久”表示“重新启动后会存在”,那么Guava Cache不适合你,因为它是内存缓存。 Just remove expireAfte ...
  • 这不行。 “访问”表示“读取或写入访问”,当它在读取后立即过期时,它也会在写入后立即过期。 您可以手动删除该条目。 您可以使用asMap()视图在单个访问中执行此操作: String getAndClear(String key) { String[] result = {null}; cache.asMap().compute(key, (k, v) -> result[0] = v; return null; }); return ...
  • Guava缓存将值存储在RAM中。 请参阅https://github.com/google/guava/wiki/CachesExplained#applicability 。 Guava Caches store values in RAM. See https://github.com/google/guava/wiki/CachesExplained#applicability.
  • 来吧,使用多个缓存。 没有“令人讨厌的谷歌设计的缓存管理内容”,你会看到你是否看过源代码。 Go ahead, use multiple caches. There's no "nasty Google-engineered cache management stuff," as you'd see if you looked at the source code.
  • 当然。 CacheBuilder.newBuilder().maximumSize(0)将完成这项工作。 Sure. CacheBuilder.newBuilder().maximumSize(0) will do the job.
  • 我为这个问题实现了一个解决方案:在返回它之后使元素无效。 这将在插入后立即从缓存中删除该元素。 缓存配置: public Element load(String key) { return requestElement(key); } 然后: element = guavaCache.get(key); if(element.isActive == false){ guavaCache.invalidate(key) } 这似乎不是很干净,但它是由Guava在内部完成的。 I implement ...
  • 一种可能的解决方案是在RemovalListener写入脏数据。 如果完成此操作,则同步条目上的其他操作将被阻止,并且不会显示任何不一致的状态。 根据数据库的延迟,这可能会影响缓存上的其他操作,请参阅Guavas文档中的警告。 一般来说,你喜欢做的是所谓的“后写缓存”。 有一些内置此功能的缓存产品。请查看现有解决方案。 A possible solution is to write the dirty data in the RemovalListener. If this is done synchron ...
  • Guava的Cache类基于ConcurrentHashMap ,因此共享其基本行为。 我不认为这是合同的一部分,但在其中一个文档中提到过。 为了确保,我查看了源代码,确实是这样 - 代码实际上是从ConcurrentHashMap分支出来的。 我们将不得不让Guava团队中的某个人充分肯定没有任何可能是错误的角落案例,所以我会默默地认为它总是正确的。 考虑到这一点,答案很简单 - ConcurrentHashMap文档说: 检索操作(包括get() )通常不会阻塞,因此可能与更新操作重叠(包括put()和 ...
  • 因为你对com.google.guava:guava:23.3 org.seleniumhq.selenium:selenium-java:3.0.1依赖性com.google.guava:guava:23.3使用org.seleniumhq.selenium:selenium-java:3.0.1可能会让你在十字路口。 但是Selenium发行说明清楚地提到了以下番石榴依赖性: Selenium v2.49.0 :Bump guava到19版 Selenium v3.1.0 :需要更新最新的番石榴版本21 ...
  • AbstractScheduledServiced实现Service 。 Service接口描述了生命周期方法,包括startAsync 。 ServiceState枚举文字包含有关其含义的文档。 处于NEW状态的服务(刚刚创建): 处于此状态的服务处于非活动状态。 它做的工作量极少,占用资源极少。 要使服务执行某些有用的操作,您必须将其转换为RUNNING状态 此状态下的服务正在运行。 这就是为什么你必须在它做任何事之前启动服务的原因。 我还建议不要从构造函数中调用startAsync,而是从创建MySe ...