0

我正在使用 Java WebFlux 2.5.2 版。我需要提取作为 POST 请求的纯文本,然后我必须处理文本。如何从 ServerRequest 对象中提取正文?

我正在粘贴我的路由器和处理程序代码。将图像附加到显示我尝试提取有效负载的代码的错误的监视窗口中。

在此处输入图像描述

路由器类如下:

package com.test;

import com.test.AppHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

import static org.springframework.web.reactive.function.server.RequestPredicates.*;

@Configuration
public class AppRouter {

    @Bean
    public RouterFunction<ServerResponse> route(AppHandler appHandler){
        return RouterFunctions
                .route(GET("/").and(accept(MediaType.TEXT_PLAIN)), appHandler::ping)
                .andRoute(POST("/process").and(accept(MediaType.ALL)).and(contentType(MediaType.TEXT_PLAIN)), appHandler::process);
    }

}

处理程序类如下:

package com.test;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;



@Component
public class AppHandler {


    public Mono<ServerResponse> process(ServerRequest request){

        //Extract the request body
        Mono<String> responseBody = request.bodyToMono(String.class);
        responseBody.map(s -> s + " -- added on the server side.");

        return ServerResponse.ok()
                .body(responseBody.log(), String.class);

    }

    public Mono<ServerResponse> ping(ServerRequest request){
        return ServerResponse.ok()
                .contentType(MediaType.TEXT_PLAIN)
                .body(Mono.just("PONG").log(), String.class);
    }


}

pom依赖的提取

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.2</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>
    ...
<dependencies>
4

1 回答 1

2

您发布的错误不是来自您发布的代码。您不允许在反应式应用程序中进行阻塞,并且您使用了关键字block,这意味着您得到了一个,IllegalStateException因为阻塞是非法的。

然后在您发布的代码中,问题是您正在破坏链条。

responseBody.map(s -> s + " -- added on the server side.");

此行只是一个声明,但是nothing happens until you subscribe,并没有订阅此行,因此您需要跟进并处理 map 函数的返回。

return responseBody.flatMap(s -> {
    return ServerResponse.ok()
        .body(Mono.just(s + " -- added on the server side."), String.class);
});

当客户端调用您的应用程序时,他们正在订阅,因此您必须确保链在服务器端是完整的,以便我们可以将项目提供给客户端。但是你没有处理上面一行中的退货,所以什么都没有发生。

于 2021-07-01T22:54:30.120 回答