Multithreading Schedulers.BoundedElistic似乎使用同一线程进行处理
通过查看API,我的理解是使用Schedulers.boundedElastic()或Schedulers.newBoundedElastic(3,10,“MyThreadGroup”);fromExecutor(executor)允许在多个线程中处理IO操作 但是,使用以下示例代码进行的模拟似乎表明一个线程/同一个线程正在flatMap中执行此工作Multithreading Schedulers.BoundedElistic似乎使用同一线程进行处理,multithreading,spring-webflux,project-reactor,Multithreading,Spring Webflux,Project Reactor,通过查看API,我的理解是使用Schedulers.boundedElastic()或Schedulers.newBoundedElastic(3,10,“MyThreadGroup”);fromExecutor(executor)允许在多个线程中处理IO操作 但是,使用以下示例代码进行的模拟似乎表明一个线程/同一个线程正在flatMap中执行此工作 Flux.range(0, 100) .flatMap(i -> {
Flux.range(0, 100)
.flatMap(i -> {
try {
// IO operation
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Mapping for " + i + " is done by thread " + Thread.currentThread().getName());
return Flux.just(i);
})
.subscribeOn(Schedulers.boundedElastic())
.subscribe();
Thread.sleep(10000); // main thread
//This yields the following
Mapping for 0 is done by thread boundedElastic-1
Mapping for 1 is done by thread boundedElastic-1
Mapping for 2 is done by thread boundedElastic-1
Mapping for 3 is done by thread boundedElastic-1 ...
上面的输出向我表明,相同的线程正在flatMap中运行。当为多个IO在subcribe上调用flatMap时,是否有一种方法可以让多个线程处理项目?我本来希望看到Boundederastic-1,Boundederastic-2。。。
.1。与非阻塞IO并发(首选) 如果您有机会使用非阻塞IO(如Spring WebClient),那么您就不必担心线程或调度程序,而且您还可以立即获得并发性: 通量范围(0,100) .flatMap(i->Mono.delay(持续时间500毫秒))//例如:反应式网络客户端调用 .doOnNext(x->System.out.println(“对“+i+”的映射由线程“+thread.currentThread()完成”) .getName())) .subscribe(); 2。阻塞IO的并发性 如果有选择,最好避免阻塞IO。如果无法避免,只需对代码稍作修改,并将
subscribeOn
应用于内部Mono
:
通量范围(0,100)
.flatMap(i->Mono.fromRunnable(()->{
试一试{
//IO操作
睡眠(500);
}捕捉(中断异常e){
e、 printStackTrace();
}
System.out.println(“对“+i+”的映射由线程“+thread.currentThread().getName()完成”);
}).subscribeOn(Schedulers.boundedElastic())
.subscribe();
让flatMap在多个线程上运行的一种方法是创建一个ParallelFlux。下面的示例代码实现了这一点
Flux.range(0, 1000)
.parallel()
.runOn(Schedulers.boundedElastic())
.flatMap(i -> {
try {
// IO operation
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("second Mapping for " + i + " is done by thread " + Thread.currentThread().getName());
return Flux.just(i);
})
.subscribe();
Thread.sleep(10000);
可能的重复flatMap是
异步的
它不是并行的
,除非你有大量的cpu计算能力,否则你不会从并行执行中获得任何好处,对于I/O工作,如文件读取或rest调用,线程大多会等待响应,这不需要并行执行,相反,flatMap提供了优化的异步执行。我认为可以从多个线程处理需要执行IO操作的独立发射元素中获益。我并没有声称不需要多个线程。你从哪儿弄来的?线程是必不可少的,但在reactor中,线程不做工作,线程调度工作。事件循环完成了这项工作,它是单线程的。什么是最有效的取决于所做的工作。在webflux应用程序的高负载情况下,framwork将尽可能高效地安排工作。异步工作和并行工作之间存在巨大差异。ParallelFlux不用于阻塞IO。