【发布时间】:2021-09-11 18:34:09
【问题描述】:
我在 Spring 中有基本的 rest 控制器。为了试用 spring webflux 并了解它的非阻塞性质。我创建了两个控制器映射,一个用于读取,一个用于服务 webclient 调用(如下所示)
@GetMapping("/slow-service-tweets")
private List<String> getAllTweets() {
try {
Thread.sleep(2000L); // delay
} catch (InterruptedException e) {
e.printStackTrace();
}
return Arrays.asList(
"Item1", "Item2","Item3");
}
这是我的测试get api,它只是触发下面给出的代码(第一个版本)
@GetMapping("/test")
public void doSomething(){
log.info("Starting NON-BLOCKING Controller!");
Flux<String> tweetFlux = WebClient.create()
.get()
.uri("http://localhost:9090/slow-service-tweets")
.retrieve()
.bodyToFlux(String.class);
tweetFlux.subscribe(tweet ->{
try {
log.info("i am back");
Thread.sleep(6000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info(tweet.toString());});
log.info("Exiting NON-BLOCKING Controller!");
以上代码的行为与它应该的完全一样。输出是
Starting NON-BLOCKING Controller!
Exiting NON-BLOCKING Controller!
Item1
Item2
Item3
原因是线程不会阻止订阅通量并继续前进。 现在请看下面的第二个版本。
@GetMapping("/test")
public void doSomething(){
System.out.println("i am here");
Flux<Integer> f= Flux.just(1,2,3,4,5);
// Flux<Integer> f= Flux.fromIterable(testService.returnStaticList());
f.subscribe(consumer->{
try {
log.info("consuming");
Thread.sleep(2000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info(consumer);
});
log.info("doing something else");
}
最好像前面的例子 “做其他事情”必须立即打印。 但无论我做什么,打印所有元素都需要 10 秒,然后打印“做其他事情”。输出如下:
i am here
consuming
1
2
3
4
5
doing something else
谁能解释一下我在这里缺少什么?
【问题讨论】:
标签: java spring-webflux project-reactor flux