Akka Java File IO Throttling



我想逐行将文件内容流式传输到Actor。我有类似的东西:

final ActorSystem system = ActorSystem.create("stream_system");
final Materializer materializer = ActorMaterializer.create(system);
final ActorRef actor = system.actorOf(Props.create(streamActor.class), "sink");
final Path file = Paths.get("path/file.txt");
Sink<ByteString, CompletionStage<Done>> printlnSink =
        Sink.<ByteString> foreach(chunk -> actor.tell(chunk.utf8String(), null));
        //Sink.<ByteString> actorRef(actor, null);
CompletionStage<IOResult> ioResult =
        FileIO.fromPath(file)
                .throttle(1, Duration.create(1, TimeUnit.SECONDS), 1, ThrottleMode.shaping())
                .to(printlnSink)
                .run(materializer);

未注释的版本有效,但它可以一次性流式传输整个文件内容。注释版本最终显示"未知"消息。

我想在几秒钟的延迟内逐行发送给Actor。任何帮助如何实现这一目标?接收演员只需获取字符串消息并将其打印在输出上。

Framing类可以帮助您:

CompletionStage<IOResult> ioResult =
    FileIO.fromPath(file)
          .via(Framing.delimiter(ByteString.fromString(System.lineSeparator()), 1000, FramingTruncation.ALLOW))
          .throttle(1, Duration.create(1, TimeUnit.SECONDS), 1, ThrottleMode.shaping())
          .to(printlnSink)
          .run(materializer);

最新更新