[英]Spring Webflux Callable not working for async
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”,但是会输出 {}。 在我的控制台打印“Callable”但没有打印“Async” 请帮助我为什么我的代码不起作用?
我添加了我的 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)。 您可以通过提供这样的Callable
来创建Mono
:
@GetMapping("/callable")
public Mono<String> callable() throws InterruptedException {
log.info("callable");
return Mono.fromCallable(() -> {
log.info("async");
Thread.sleep(2000);
return "hello";
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.