【问题标题】:Composing futures with possible failures in Akka with Java使用 Java 在 Akka 中组合可能失败的期货
【发布时间】:2023-03-14 04:35:01
【问题描述】:

我正在尝试在我自己的应用程序中应用未来的组合概念。根据 Akka 文档,您可以这样做 (http://doc.akka.io/docs/akka/snapshot/java/futures.html):

final ExecutionContext ec = system.dispatcher();
//Some source generating a sequence of Future<Integer>:s
Iterable<Future<Integer>> listOfFutureInts = source;

// now we have a Future[Iterable[Integer]]
Future<Iterable<Integer>> futureListOfInts = sequence(listOfFutureInts, ec);

// Find the sum of the odd numbers
Future<Long> futureSum = futureListOfInts.map(
     new Mapper<Iterable<Integer>, Long>() {
          public Long apply(Iterable<Integer> ints) {
              long sum = 0;
              for (Integer i : ints)
                   sum += i;
              return sum;
         }
     }, ec);

futureSum.onSuccess(new PrintResult<Long>(), system.dispatcher());

请记住,我正在使用 Akka 的 Java 版本进行开发,因为我对 Scala 不够熟悉。 当您想要构建成功的期货时,这很好用。在这里,您只是聚合所有期货(整数​​)的结果并将它们相加并将其结果放在另一个可以稍后处理的未来中。现在,如果其中一个期货可能失败会发生什么,即抛出异常。当然,您可以使用 'onFailure' 回调来处理任何特定未来的失败,但我还没有找到一种方法来处理组合未来时的失败。

最好的方法是什么?我应该完全应用另一个概念吗?

谢谢。

【问题讨论】:

    标签: java akka future


    【解决方案1】:

    您正在寻找recoverrecoverWith,如下所述:http://doc.akka.io/docs/akka/2.3.2/java/futures.html#Exceptions

    final ExecutionContext ec = system.dispatcher();
    
    Future<Integer> future = future(new Callable<Integer>() {
      public Integer call() {
        return 1 / 0;
      }
    }, ec).recover(new Recover<Integer>() {
      public Integer recover(Throwable problem) throws Throwable {
        if (problem instanceof ArithmeticException)
          return 0;
        else
          throw problem;
      }
    }, ec);
    
    future.onSuccess(new PrintResult<Integer>(), system.dispatcher());
    

    【讨论】:

    • 谢谢!我会继续尝试这个。您如何看待在消息中包装异常并让参与者来回传递包装的异常?这样,至少在这个例子中,我可以在我的 apply 函数中处理我未来的所有响应?
    • 您好,我不明白您的问题与演员有什么关系。我建议尽可能少地混合两者,它们是两种完全不同的范式。
    猜你喜欢
    • 2018-06-11
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多