4

我编写了一个程序来使用 Google Guava 缓存对象。我的问题是如何将附加参数传递给 Guava Load 方法。这是代码。下面你在这一行中看到 - 我已将 fileId 和 pageno 作为键 - cache.get(fileID+pageNo);。现在,当 cache.get 被调用并且该键不在缓存中时 - 番石榴将调用我在下面给出的类 PreviewCacheLoader 的加载方法。

public class PreviewCache {
    static final LoadingCache<String, CoreObject> cache = CacheBuilder.newBuilder()
          .maximumSize(1000)
          .expireAfterWrite(5, TimeUnit.MINUTES) 
          .build(new PreviewCacheLoader());

   public CoreObject getPreview(String strTempPath, int pageNo, int requiredHeight, String fileID, String strFileExt,  String ssoId) throws IOException 
    {
        CoreObject coreObject = null;
        try {
            coreObject = cache.get(fileID+pageNo, HOW TO PASS pageNO and requiredHeight because I want to keep key as ONLY fileID+pageNo );
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return coreObject;
    }
}

除了关键参数之外,如何将上面的 int 和 String 参数传递给下面的 Load 方法

public class PreviewCacheLoader extends CacheLoader<String, CoreObject> {

@Override
public CoreObject load(String fileIDpageNo, HOW TO GET pageNO and requiredHeight) throws Exception {

    CoreObject coreObject = new CoreObject();
    // MAKE USE OF PARAMETERS pageNO and requiredHeight
    // Populate coreObject here 
    return coreObject;


}

}

4

1 回答 1

3

fileId + pageNo对于初学者来说,将其用作String键而不是创建适当的对象是非常糟糕的编程习惯。(这称为“字符串类型”代码。)解决问题的最佳方法可能如下所示:

class FileIdAndPageNo {
  private final String fileId;
  private final int pageNo;
  ...constructor, hashCode, equals...
}
public CoreObject getPreview(final int pageNo, final int requiredHeight, String fileID) { throws IOException 
{
    CoreObject coreObject = null;
    try {
        coreObject = cache.get(new FileIdAndPageNo(fileID, pageNo),
           new Callable<CoreObject>() {
             public CoreObject call() throws Exception {
               // you have access to pageNo and requiredHeight here
             }
           });
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    return coreObject;
}
于 2013-08-30T01:07:32.093 回答