gpt4 book ai didi

java - 如何用 Java 返回我自己的 future ?

转载 作者:搜寻专家 更新时间:2023-11-01 02:40:52 24 4
gpt4 key购买 nike

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

最佳答案

既然您使用的是 Guava 的 ListenableFuture,最简单的解决方案是 transform来自 Futures 的方法:

Returns a new ListenableFuture whose result is the product of applying the given Function to the result of the given 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);
}

关于java - 如何用 Java 返回我自己的 future ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33487969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com