java – Google Guava – 将参数传递给load方法另外转到KEY

我编写了一个使用Google Guava缓存对象的程序.我的问题是如何将其他参数传递给Guava Load方法.这是代码.下面你看到这一行 – 我把fileId和pageno作为键 – cache.get(fileID pageNo);.现在当调用cache.get并且当该键不在缓存中时–guava将调用我在下面给出的类PreviewCacheLoader的load方法.

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;
    }
}

除了key参数之外,如何将上面的参数从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;


}

}

最佳答案 对于初学者来说,使用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;
}
点赞