gpt4 book ai didi

java - 如何从 Akka Streams Sink 中抛出的异常中恢复?

转载 作者:行者123 更新时间:2023-12-02 01:00:27 25 4
gpt4 key购买 nike

如何从 Akka Streams 的 Sink 中抛出的异常中恢复?

简单示例:

    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)

最佳答案

默认情况下,supervision strategy当抛出异常时停止流。要更改监督策略以删除导致异常的消息并继续处理下一条消息,请使用“恢复”策略。例如:

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();
};

关于java - 如何从 Akka Streams Sink 中抛出的异常中恢复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60707839/

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