如何在 Java 中返回我自己的 future?

Hap*_*eer 5 java concurrency future

在 Java 8 中,我正在编写一个 DAO 方法,该方法调用返回 ListenableFuture 的方法(在本例中,它是返回 ResultSetFuture 的 Cassandra 异步查询)。

但是,我一直困惑于如何将 Future 返回给 DAO 方法的调用者。我不能只返回 ResultSetFuture,因为该 future 返回一个 ResultSet。我想处理 ResultSet 并返回一个不同的对象。例如:

public ListenableFuture<ThingObj> queryForThingAsync(String thingId) {
    ListenableFuture<ResultSet> rsFuture = db.getSession().executeAsync(QueryBuilder.select().all().from("thingSchema","Thing").where(eq("thingId",thingId)));
    // Now what? How do I create a ListenableFuture<ThingObj> given a ListenableFuture<ResultSet> and a method that can convert a ResultSet into a ThingObj?
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*m G 4

因为看起来您正在使用 Guava 的ListenableFuture,所以最简单的解决方案是来自的转换方法Futures

返回一个新的 ListenableFuture ,其结果是将给定 Function 应用于给定 Future 的结果的乘积。

有几种方法可以使用它,但由于您使用的是 Java 8,最简单的方法可能是使用方法引用:

public ListenableFuture<ThingObj> queryForThingAsync(String thingId) {
    ListenableFuture<ResultSet> rsFuture = db.getSession().executeAsync(QueryBuilder.select().all().from("thingSchema","Thing").where(eq("thingId",thingId)));
    return Futures.transform(rsFuture, Utils::convertToThingObj);
}
Run Code Online (Sandbox Code Playgroud)