【问题标题】:How to read file lines while they appear and represent them as Flux?如何在文件行出现并将它们表示为 Flux 时读取它们?
【发布时间】:2020-09-15 07:26:37
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 实现一些tail -f 功能(大量资源以不同的方式实现),将行传递给processor(或使用generate

标签: java project-reactor flux spring-reactor


【解决方案1】:

你可以像这样使用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();

【讨论】:

    猜你喜欢
    • 2021-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多