如何使用番石榴缓存GWT中的服务器结果?

时间:2016-01-18 09:23:57

标签: java caching gwt guava

在我的GWT应用程序中,我经常多次引用相同的服务器结果。我也不知道先执行哪个代码。因此,我想使用我的异步(客户端)结果的缓存。

我想使用现有的缓存库;我正在考虑 guava-gwt

我发现了一个Guava 同步缓存的示例(在guava's documentation中):

LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
       .build(
           new CacheLoader<Key, Graph>() {
             public Graph load(Key key) throws AnyException {
               return createExpensiveGraph(key);
             }
           });

这就是我尝试使用Guava缓存异步的方法(我不知道如何使这项工作):

LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
       .build(
           new CacheLoader<Key, Graph>() {
             public Graph load(Key key) throws AnyException {

               // I want to do something asynchronous here, I cannot use Thread.sleep in the browser/JavaScript environment.
               service.createExpensiveGraph(key, new AsyncCallback<Graph>() {

                 public void onFailure(Throwable caught) {
                   // how to tell the cache about the failure???
                 }

                 public void onSuccess(Graph result) {
                   // how to fill the cache with that result???
                 }
               });

               return // I cannot provide any result yet. What can I return???
             }
           });

GWT缺少默认JRE中的许多类(特别是关于线程和并发性)。

如何使用guava-gwt缓存异步结果?

2 个答案:

答案 0 :(得分:5)

据我所知,你想要实现的不只是异步缓存,而且还是一个惰性缓存,并且创建一个GWT并不是最好的地方,因为在实现具有客户端异步执行的GWT应用程序时存在很大问题,因为GWT缺少Future和/或Rx组件的客户端实现(仍然存在一些用于GWT的RxJava实现)。所以在通常的java中你想要创建的东西可以通过以下方式实现:

LoadingCache<String, Future<String>> graphs = CacheBuilder.newBuilder().build(new CacheLoader<String, Future<String>>() {
    public Future<String> load(String key) {
        ExecutorService service = Executors.newSingleThreadExecutor();
        return  service.submit(()->service.createExpensiveGraph(key));
    }
});
Future<String> value = graphs.get("Some Key");
if(value.isDone()){
    // This will block the execution until data is loaded 
    String success = value.get();           
}

但是由于GWT没有Future的实现,你需要创建一个就像

一样
public class FutureResult<T> implements AsyncCallback<T> {
    private enum State {
        SUCCEEDED, FAILED, INCOMPLETE;
    }

    private State state = State.INCOMPLETE;
    private LinkedHashSet<AsyncCallback<T>> listeners = new LinkedHashSet<AsyncCallback<T>>();
    private T value;
    private Throwable error;

    public T get() {
        switch (state) {
        case INCOMPLETE:
            // Do not block browser so just throw ex
            throw new IllegalStateException("The server response did not yet recieved.");
        case FAILED: {
            throw new IllegalStateException(error);
        }
        case SUCCEEDED:
            return value;
        }
        throw new IllegalStateException("Something very unclear");
    }

    public void addCallback(AsyncCallback<T> callback) {
       if (callback == null) return;
       listeners.add(callback);
    }

    public boolean isDone() {
        return state == State.SUCCEEDED;
    }

    public void onFailure(Throwable caught) {
        state = State.FAILED;
        error = caught;
        for (AsyncCallback<T> callback : listeners) {
            callback.onFailure(caught);
        }
    }

    public void onSuccess(T result) {
        this.value = result;
        state = State.SUCCEEDED;
        for (AsyncCallback<T> callback : listeners) {
            callback.onSuccess(value);
        }
    }

}

您的实施将变为:

    LoadingCache<String, FutureResult<String>> graphs = CacheBuilder.newBuilder().build(new CacheLoader<String, FutureResult<String>>() {
        public FutureResult<String> load(String key) {
            FutureResult<String> result = new FutureResult<String>();
            return service.createExpensiveGraph(key, result);
        }
    });

    FutureResult<String> value = graphs.get("Some Key");

    // add a custom handler
    value.addCallback(new AsyncCallback<String>() {
        public void onSuccess(String result) {
            // do something
        }
        public void onFailure(Throwable caught) {
            // do something             
        }
    });
    // or see if it is already loaded / do not wait 
    if (value.isDone()) {
        String success = value.get();
    }

使用FutureResult时,您不仅会缓存执行,还会产生某种懒惰,因此您可以在数据加载到缓存时显示一些loading screen

答案 1 :(得分:0)

如果你只需要缓存异步调用结果,你可以去找一个 非加载缓存,而不是加载缓存

在这种情况下,您需要使用 put,getIfPresent 方法来存储和检索缓存中的记录。

String v = cache.getIfPresent("one");
// returns null
cache.put("one", "1");
v = cache.getIfPresent("one");
// returns "1"

或者,可以在缓存未命中 Callable 上加载新值

String v = cache.get(key,
    new Callable<String>() {
        public String call() {
        return key.toLowerCase();
    }
});

供进一步参考:https://guava-libraries.googlecode.com/files/JavaCachingwithGuava.pdf