如何在文件行出现时读取它们并将它们表示为 Flux?

How to read file lines while they appear and represent them as Flux?

假设我们依赖 Reactor 3(即在 Spring 5 应用程序中)和文本文件 my/file.txt.

我需要订阅文本文件行(现有行和将来会出现的行)并创建一个 Flux<String>。如果你愿意,忽略阻塞IO读取问题,让我们揭示构建这种订阅的原理。

为简单起见,假设我们将这些行打印到标准输出:

flowLinesFrom(Path.of("my/file.txt"))
   .subscribe(System.out::println);     

实施Flux<String> flowLinesFrom(Path)的正确方法是什么?

你可以像这样使用this

//Create FluxTailer
FluxTailer tailer = new FluxTailer(
    //The file to tail
    Path.of("my/file.txt").toFile(),
    //Polling interval for changes
    Duration.ofSeconds(1)
);

//Start tailing
tailer.start();

//Subscribe to the tailer flux
tailer.flux().subscribe(System.out::println);

//Just for demo you wait for 10 seconds
try{
    Thread.sleep(10000);
}catch (Exception e){}

//Stop the tailer when done, will also complete the flux
tailer.stop();

您可以随意开始停止,也可以使用

设置从文件的开头或结尾读取
tailer.readFromStart();
tailer.readFromEnd();