java - 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秒后会输出“Hello”,但会输出{}。在我的控制台中打印“可调用”但未打印“异步”请帮助我为什么我的代码不起作用?
我添加我的 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 期望控制器返回一个 Publisher(Mono/Flux)。您可以Mono
通过提供Callable
这样的来创建:
@GetMapping("/callable")
public Mono<String> callable() throws InterruptedException {
log.info("callable");
return Mono.fromCallable(() -> {
log.info("async");
Thread.sleep(2000);
return "hello";
});
}
作为旁注,Thread.sleep
不应该在实际应用程序代码的反应式管道中使用。
推荐阅读
- python - 访问存储在 Dataframe 中的对象的属性
- python - 在 Python 上的 WordCloud 中,我想合并两种语言
- python-3.x - 无法通过 python 3 的 pymqi 版本使用 SSL 连接到公共队列
- c - How to initialize multiple arrays with unknown sizes via a function in C
- snowflake-cloud-data-platform - 读者账户和消费者账户有什么区别
- uber-api - watchOS 6.2 上使用 ASWebAuthenticationSession 的 Uber API OAuth
- java - Which Java API from the Azure SDK to manage PostgreSQL servers?
- python - MQTT 发布者是否可以在主题上定义允许的订阅者?
- ios - UIWebView 的 scalesPageToFit 但设置为 FALSE 的等效 WKWebView
- c# - 如何在 Wix 自定义引导程序应用程序中进行捆绑更新?