等一些Spring ListenableFuture

时间:2017-04-11 11:48:17

标签: spring completable-future spring-web asyncresttemplate

有一项服务使用Spring AsyncRestTemplate发送休息呼叫。 AsyncRestTemplate.exchange()的每次通话都会返回ListenableFuture。像这样:

    ListenableFuture future1 = new AsyncRestTemplate().exchange(...);
    ListenableFuture future2 = new AsyncRestTemplate().exchange(...);
    ListenableFuture future3 = new AsyncRestTemplate().exchange(...);

有没有办法创建单ListenableFuture组合所有其他调用?来自Guava的Futures.allAsList

2 个答案:

答案 0 :(得分:1)

步骤1:将每个ListenableFuture转换为CompletableFuture

public CompletableFuture<T> toCompletableFuture(ListenableFuture<ResponseEntity<String>> listenableFuture) {
    final CompletableFuture<T> completableFuture = new CompletableFuture<>();

    listenableFuture.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
        @Override
        public void onFailure(Throwable e) {
            completableFuture.completeExceptionally(e);
            }
        }

        @Override
        public void onSuccess(ResponseEntity<String> result) {
            completableFuture.complete(parseResponse(result));
            }
        }
    });
    return completableFuture;
}

步骤2:调用CompletableFuture.allOf(cF1,cF2,cF3 ......)

答案 1 :(得分:0)

从Spring 5.0开始,ListenableFuture实现了completable()方法,该方法完全可以满足您的需求:

    /**
     * Expose this {@link ListenableFuture} as a JDK {@link CompletableFuture}.
     * @since 5.0
     */
    default CompletableFuture<T> completable() {