如果您希望每个重复的通量位于不同的线程上,您可以将publishOn 移到前面,如下所示:
Flux.just(1,2,3,4,5,6,7,8)
.publishOn(Schedulers.parallel()) // <- before
.flatMap(integer -> {
System.out.println("val:" + integer + ", thread:" + Thread.currentThread().getId());
return Mono.just(integer);
}, 5)
.repeat()
.subscribe();
现在的输出是这样的:
val:1, thread:20
val:2, thread:20
val:3, thread:20
val:4, thread:20
val:5, thread:20
val:6, thread:20
val:7, thread:20
val:8, thread:20
val:1, thread:13
val:2, thread:13
val:3, thread:13
val:4, thread:13
val:5, thread:13
val:6, thread:13
val:7, thread:13
val:8, thread:13
如果您希望每个整数位于不同的线程中,您可以执行以下操作:
Flux.just(1,2,3,4,5,6,7,8)
.publishOn(Schedulers.parallel()) // <- Each flux can be published in a different thread
.flatMap(integer -> {
return Mono.fromCallable(() -> {
System.out.println("val:" + integer + ", thread:" + Thread.currentThread().getId());
return integer;
}).publishOn(Schedulers.parallel()); // <- Each Mono processing every integer can be processed in a different thread
})
.repeat()
.subscribe();
输出变成:
val:3, thread:16
val:2, thread:15
val:7, thread:20
val:8, thread:13
val:5, thread:18
val:6, thread:19
val:3, thread:17
val:5, thread:19
val:6, thread:20
val:1, thread:15
val:8, thread:14
val:4, thread:18
val:7, thread:13