Spring Webflux Callable不适用于异步


package demo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.Callable;
@SpringBootApplication
@Slf4j
@EnableAsync
public class DemoApplication {
@RestController
public static class MyController {
@GetMapping("/callable")
public Callable<String> callable() throws InterruptedException {
log.info("callable");
return ()-> {
log.info("async");
Thread.sleep(2000);
return "hello";
};
}
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

上面的代码是spring项目的代码。我预测,当调用http://localhost:8080/callable时;你好"将在2秒内输出,但将输出{}。在我的控制台上;可调用的";但未打印";异步";请帮我为什么我的代码不起作用??

我添加我的pom.xml文件

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>

WebFlux期望控制器返回发布服务器(Mono/Flux(。您可以通过提供如下Callable来创建Mono

@GetMapping("/callable")
public Mono<String> callable() throws InterruptedException {
log.info("callable");
return Mono.fromCallable(() -> {
log.info("async");
Thread.sleep(2000);
return "hello";
});
}

附带说明一下,在实际的应用程序代码中,Thread.sleep不应该在反应管道中使用。

最新更新