编程语言
首页 > 编程语言> > Java Reactor:如何从stdin生成Flux?

Java Reactor:如何从stdin生成Flux?

作者:互联网

我想异步读取用户从stdin生成的消息.
就像是:

Flux.from(stdinPublisher()) 
    .subscribe(msg -> System.out.println("Received: " + msg));

那么如何在这里实现这样的stdin发布者呢?

解决方法:

很容易.对不起打扰:)

import java.util.Scanner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

@Component
@Slf4j
public class StdinProducerExample implements ApplicationRunner {

  @Override
  public void run(ApplicationArguments args) throws Exception {
    Flux
        .create(sink -> {
          Scanner scanner = new Scanner(System.in);
          while (scanner.hasNext()) {
            sink.next(scanner.nextLine());
          }
        })
        .subscribeOn(Schedulers.newSingle("stdin publisher"))
        .subscribe(m -> log.info("User message: {}", m));
    log.info("Started listening stdin");
  }

}

标签:project-reactor,spring-webflux,java
来源: https://codeday.me/bug/20190731/1587807.html