Spring WebFlux - 如何从 Handler 类返回 Flux 响应

问题描述 投票:0回答:1

我想使用 Spring WebFlux 来实现 CRUD 操作,同时编写传统的控制器和新的处理程序路由类。我理解 Mono 代表 0,1 个项目,Flux 代表 0 到 n 个项目。

我的用例是从数据库中获取员工列表并将它们作为 Flux 返回。

我关注了这个网站,它对于编写传统控制器效果很好 - https://howtodoinjava.com/spring-webflux/spring-webflux-tutorial/

@RequestMapping(value = { "/findAll"}, method = RequestMethod.GET)
    public Flux<Employee> findAll() {
        return employeeService.findAll();
    }

但是当我尝试使用处理程序和路由执行相同操作时,我看到如下错误

Route
-----
@Bean
    public RouterFunction<ServerResponse> route3(EmploeeHandler emploeeHandler) {
        System.out.println("findAll2");
        return RouterFunctions.route(GET("/findAll2").and(accept(MediaType.APPLICATION_JSON)),
                emploeeHandler::findAll2);
    }

Handler
-------
public Flux<ServerResponse> findAll2(ServerRequest request) {
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
        .body(employeeService.findAll(), Employee.class);
                
}

Type mismatch: cannot convert from Mono<ServerResponse> to Flux<ServerResponse>

在 ServerResponse 中将 Flux 转换为 Mono 可以解决这个问题。我想使用 Flux,因为数据库中可能有很多员工。谁能解释一下我在这里缺少什么吗?

java spring-boot spring-webflux
1个回答
0
投票

即使您正在流式传输许多

Employee
对象(您正在使用存储库/服务调用
employeeService.findAll()
执行此操作),当您将
Flux<Employee>
放入响应中时,这仍然被视为单个响应。

这里有一个类比: 想象一下,您要发送一个包含多个物品的包裹。包裹本身是一个

Mono
- 它只是一个包裹。但里面的物品可以看作是一个
Flux
——里面可以有0到n个物品。

这就是为什么在处理程序方法签名中将

Flux<ServerResponse>
更改为
Mono<ServerResponse>
实际上是您想要在此处执行的操作。

PS:我不是不喜欢这个问题的人。

© www.soinside.com 2019 - 2024. All rights reserved.