当打印日志时,项目反应器总是在主线程中运行



我是项目反应堆的新手,当我研究项目反应堆时,我观察到一件事,总是项目矢量日志得到打印作为主要步骤。如果反应堆在不关心线程的情况下运行,那是怎么发生的?以及我如何得到验证的响应代码运行在不同的不同线程?

作为默认反应器基于您订阅的线程运行。如果您从自己的线程订阅,则反应器将基于该线程运行。这意味着不是每次主线程。您可以运行此测试代码来验证这一点。这是在主线程上创建的通量。这个流量是从新创建的另一个线程订阅的。运行应用程序后,查看日志。日志会证明的。日志已经在我们新创建的线程上运行了。

public void testTheThread() throws InterruptedException {
//the flux created on the main thread.
Flux<String> stringFlux = Flux
.fromArray(new String[]{"a", "b"})
.map(String::toUpperCase)
.log();
//the subscriber runs on another new thread. [my-new-thread]
Thread newThread = new Thread(() -> {
stringFlux.subscribe(s -> {
System.out.println("String is  = " + s);
});
});
newThread.setName("my-new-thread");
newThread.start();
//sleep the main thread until get the data from my-new-thread
//otherwise the log will not be printed.
Thread.sleep(1000);
}

日志将是这样的。

17:04:30.867 [my-new-thread] INFO reactor.Flux.MapFuseable.1 - | onSubscribe([Fuseable] FluxMapFuseable.MapFuseableSubscriber)
17:04:30.874 [my-new-thread] INFO reactor.Flux.MapFuseable.1 - | request(unbounded)
17:04:30.874 [my-new-thread] INFO reactor.Flux.MapFuseable.1 - | onNext(A)
s = A
17:04:30.880 [my-new-thread] INFO reactor.Flux.MapFuseable.1 - | onNext(B)
s = B
17:04:30.881 [my-new-thread] INFO reactor.Flux.MapFuseable.1 - | onComplete()
Process finished with exit code 0

最新更新