首页 > 解决方案 > 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>

标签: javaspringspring-webflux

解决方案


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不应该在实际应用程序代码的反应式管道中使用。


推荐阅读