简体   繁体   English

如何在Java中返回自己的未来?

[英]How do I return my own futures in Java?

In Java 8, I'm writing a DAO method which calls a method that returns a ListenableFuture (in this case it's a Cassandra async query that returns a ResultSetFuture). 在Java 8中,我正在编写一个DAO方法,该方法调用一个返回ListenableFuture的方法(在这种情况下,它是一个返回ResultSetFuture的Cassandra异步查询)。

However, I'm stuck on how I'm supposed to return a Future to the caller of the DAO method. 但是,我坚持认为我应该如何将Future返回给DAO方法的调用者。 I can't just return the ResultSetFuture because that future returns a ResultSet. 我不能只返回ResultSetFuture,因为将来会返回一个ResultSet。 I want to process the ResultSet and return a different object. 我想处理ResultSet并返回一个不同的对象。 For example: 例如:

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

Since it appears you're using Guava's ListenableFuture , the easiest solution is the transform method from Futures : 由于看起来你正在使用Guava的ListenableFuture ,最简单的解决方案是来自Futures转换方法:

Returns a new ListenableFuture whose result is the product of applying the given Function to the result of the given Future. 返回一个新的ListenableFuture,其结果是将给定Function应用于给定Future的结果的乘积。

There are a few ways to use it, but since you're on Java 8, the simplest is likely with a method reference: 有几种方法可以使用它,但由于您使用的是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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM