【问题标题】:How to convert request object to model Spring Webflux如何将请求对象转换为模型 Spring Webflux
【发布时间】:2018-10-05 16:58:30
【问题描述】:

我的 RestController 有一个请求对象 (DTO),我需要转换为我的模型对象(MongoDB 文档),但是使用 Spring Webflux 进行此转换而不阻塞 I/O 的正确方法是什么?

我想到了一些事情:

我的 DTO 作为发布者(单声道),然后我转换为我的模型并调用我的业务层:

@PostMapping("/persons")
public Mono<ResponseEntity<Void>> save(@RequestBody Mono<PersonRequest> request) {
    return request.map(r -> Person.builder()
                        .id(r.getId())
                        .name(r.getName())
                        .build())
            .flatMap(personService::save)
            .map(p -> ResponseEntity.ok().build());
}

或者我的 DTO 不需要成为发布者?

@PostMapping("/persons")
public Mono<ResponseEntity<Void>> save(@RequestBody PersonRequest request) {
    return personService.save(Person.builder()
                        .id(request.getId())
                        .name(request.getName())
                        .build())
            .map(p -> ResponseEntity.ok().build());
}

【问题讨论】:

  • 如果您使用的是经典的带注释的控制器,请直接使用 DTO。没有必要把事情复杂化。 Handler方法一般使用ServerRequest.monoToClass等

标签: java spring spring-webflux project-reactor


【解决方案1】:

如果您使用函数式样式而不是注释,则 ServerRequest 提供诸如 bodyToFlux(Person.class) 之类的方法,这些方法可以使用并且完全非阻塞。

如果您使用注释样式而不是如下所示:

 @PostMapping("/person")
    Mono<Void> create(@RequestBody Publisher<Person> personStream) {
            return this.repository.save(personStream).then();
    }

这是因为,正如您所说,如果您不使用 Publisher,则转换为 Person 将被阻止。 请参阅第 2.1.1 节https://docs.spring.io/spring/docs/5.0.0.RC4/spring-framework-reference/reactive-web.html

【讨论】:

  • 好的,但是如果我需要接收像 PersonRequest 这样的 DTO 并解析为 Person,我应该直接解析而不是 Mono 还是应该将 DTO 转换为 Mono 然后解析到我的模型类?我想知道如果不将我的 DTO 转换为 Mono,我将阻止我的 I/O 并且不响应。
  • 我已经编辑了回复...您是对的,如果您不使用发布者,那么转换将被阻止。
猜你喜欢
  • 2021-07-14
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 2021-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多