Java 如何从Akka Streams接收器中抛出的异常中恢复?
如何从Akka Streams接收器中抛出的异常中恢复 简单的例子:Java 如何从Akka Streams接收器中抛出的异常中恢复?,java,scala,akka,akka-stream,Java,Scala,Akka,Akka Stream,如何从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 Occu
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);
我如何处理异常并从源代码转到下一个元素?aka 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();
};
默认情况下,当抛出异常时,停止流。要更改监视策略以删除导致异常的消息并继续处理下一条消息,请使用恢复策略。例如:
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();
};
是否要跳过特定项目?然后过滤它们,查看更多细节:我不知道哪个元素会导致异常。我的接收器可能是Kafka或RabbitMq,因此如果说到rabbbitmq的连接暂时失败,那么我不想停止流,而是为未来的元素继续。是否要跳过特定的项?然后过滤它们,查看更多细节:我不知道哪个元素会导致异常。我的接收器可能是Kafka或RabbitMq,因此,如果说到rabbbitmq的连接暂时失败,那么我不想停止流,而是为将来的元素继续谢谢Jeff。有一个小小的修正:withResumingSupervision应该是Runnablegraphy类型谢谢Jeff。它做了一个小小的修正:恢复监督应为RunnableGraph类型