簡體   English   中英

如何從 Akka Streams Sink 中拋出的異常中恢復?

[英]How to recover from Exception thrown in Akka Streams Sink?

如何從 Akka Streams 的接收器中拋出的異常中恢復?

簡單示例:

    Source<Integer, NotUsed> integerSource = Source.from(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));

    integerSource.runWith(Sink.foreach(x -> {
      if (x == 4) {
        throw new Exception("Error Occurred");
      }
      System.out.println("Sink: " + x);
    }), system);

輸出:

Sink: 1
Sink: 2
Sink: 3

如何處理異常並從源移動到下一個元素? (又名 5、6、7、8、9)

默認情況下,當拋出異常時, 監督策略會停止流。 要更改監督策略以丟棄導致異常的消息並繼續處理下一條消息,請使用“恢復”策略。 例如:

final Function<Throwable, Supervision.Directive> decider =
  exc -> {
    return Supervision.resume();
  };

final Sink<Integer, CompletionStage<Done>> printSink =
  Sink.foreach(x -> {
    if (x == 4) {
      throw new Exception("Error Occurred");
    }
    System.out.println("Sink: " + x);
  });

final RunnableGraph<CompletionStage<Done>> runnableGraph =
  integerSource.toMat(printSink, Keep.right());

final RunnableGraph<CompletionStage<Done>> withResumingSupervision =
  runnableGraph.withAttributes(ActorAttributes.withSupervisionStrategy(decider));

final CompletionStage<Done> result = withResumingSupervision.run(system);

您還可以為不同類型的異常定義不同的監督策略:

final Function<Throwable, Supervision.Directive> decider =
  exc -> {
    if (exc instanceof MySpecificException) return Supervision.resume();
    else return Supervision.stop();
  };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM