小编典典

Spring Webflux和可观察到的响应不起作用

spring-boot

我刚刚使用spring-boot-starter-webflux创建了一个简单的Spring Boot应用程序,版本为2.0.0.BUILD-
SNAPSHOT,其中引入了spring-webflux版本5.0.0.BUILD-SNAPSHOT,对于Spring
Core,Beans,Context等也是如此。

如果我创建一个简单的@RestController并提供一个@GetMapping简单地返回a的a
Flux<String>,那么一切都会按预期进行。

但是,如果从更改Flux为RxJava Observable,则会出现此错误:

org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

通过代码的调试,我发现Jackson会ObjectMapper以某种方式注册FluxMono而其余的反应性类型会在其typeFactory中注册,因此后来MappingJackson2HttpMessageConverter知道了如何对它们进行反序列化。

但是,当我使用an时并非如此Observable:我找不到类型Observable或未SingleObjectMapper类型工厂中注册,因此出现上述错误。

有人遇到过这个问题吗?我会缺少依赖吗?我是否需要手动告诉Jackson如何从RxJava构造中进行(反)序列化?但是,杰克逊为什么已经了解Flux和Mono?

谢谢你的帮助。

编辑:

我正在使用RxJava 1.2.7。这是我的pom.xml:

<dependencies>
    <!-- Spring Boot -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
        <version>2.0.0.BUILD-SNAPSHOT</version>
    </dependency>
    <!-- RxJava dependeencies -->
    <dependency>
        <groupId>io.reactivex</groupId>
        <artifactId>rxjava</artifactId>
        <version>1.2.7</version>
    </dependency>
</dependencies>

这是我的控制器代码的示例:

/**
 * Get all the available tasks.
 *
 * @return the list of tasks
 */
@GetMapping(path = "/task")
@ResponseStatus(HttpStatus.OK)
public Observable<TaskView> allTasks(@AuthenticationPrincipal LoggedUserVO principal) {
    return this.pocComponent.getAllTasks()
            .map(t -> ViewConverter.convertFromTaskDocument(t, principal));
}

阅读 635

收藏
2020-05-30

共1个答案

小编典典

您可能缺少以下依赖项才能使其起作用:

<dependency>
    <groupId>io.reactivex</groupId>
    <artifactId>rxjava-reactive-streams</artifactId>
    <version>1.2.1</version>
</dependency>

各种RxJava 1.x版本的更改使我们难以开箱即用地支持它,这就是为什么我们更喜欢依赖官方的RxJava-> Reactive
Streams适配器
。请注意,支持RxJava
2.x,而无需其他依赖项(它本机构建在响应流之上)。

我将更新Spring WebFlux参考文档,以指定具有RxJava 1.x支持所需。

2020-05-30