本文介绍了是否可以使用Guava链接异步调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想链接异步休息服务调用并在完成后进行单次回调。

I want to chain async rest service calls and have single callback when they finished.

是否可以使用guava进行回调?

Is it possible to do it with guava?

推荐答案

您可以使用 Futures.chain 链接 ListenableFuture s:

final ListeningExecutorService service1 = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(16));
final ListeningExecutorService service2 = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(16));

ListenableFuture<String> service1result = service1.submit(new Callable<String>() {
    @Override
    public String call() throws Exception {
        return "service1result";
    }
});

ListenableFuture<String> service2result = Futures.chain(service1result, new Function<String, ListenableFuture<String>>() {
    @Override
    public ListenableFuture<String> apply(final @Nullable String input) {
        return service2.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return Joiner.on(" -> ").join(input, "service2result");
            }
        });
    }
});

System.out.format("Result: %s\r\n", service2result.get());

终端代码输出:

> run-main training.Training
[info] Compiling 1 Java source to /home/remeniuk/projects/guava-training/target/scala-2.9.1/classes...
[info] Running training.Training 
Result: service1result -> service2result

这篇关于是否可以使用Guava链接异步调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 09:37