java - 为什么 RestController 中的 Flux.fromIterable() 返回作为一个串联字符串返回?

标签 java spring spring-boot reactive-programming project-reactor

我有一个 Rest Conotroller,它返回 Flux<String> ,但是当我尝试将其收集到列表中时,它是所有连接的字符串中的一项。我怎样才能得到它作为一个实际的列表?

Controller :

@RestController
public class TestRestController
{
    @GetMapping( "/getflux" )
    public Flux<String> getFlux()
    {
        return Flux.fromIterable(
            Arrays.asList(
                "String 1", 
                "String 2"
            )
        );
    }
}

调用 Controller :

//This returns as a list of one item: "String 1String 2
List<String> response = WebClient.builder()
    .baseUrl( "http://localhost:" + port + "/" )
    .build()
    .get()
    .uri( "/getflux" )
    .retrieve()
    .bodyToFlux( String.class )
    .collectList()
    .block();

如何获取实际列表?

最佳答案

经过一些研究,这似乎是一个 Spring 错误,被标记为“按预期工作”。

https://github.com/spring-projects/spring-framework/issues/20807

This is expected behavior. By default byte arrays, byte buffers, and String are treated as low level content (serialized output) and is rendered as is. In fact the Flux is streamed with each string written and flushed immediately.

The Jackson encoder explicitly backs out for element type String. I realize that String and an array of String's can be rendered as JSON but there are two ways to treat String content and this is what we've chosen by default.

唯一的解决方案是永远不要返回 Flux<String>而是返回您创建的一些包装类的列表。这仍然允许使用 Flux和背压,Spring 可以正确处理如此复杂的对象。

以下效果完美:

@GetMapping("/getflux")
public Flux<List<StringWrapper>> getFlux() {
    return Flux.fromIterable(
        Arrays.asList(
            new StringWrapper( "String 1" ),
            new StringWrapper( "String 2" )

        )
    );
}

关于java - 为什么 RestController 中的 Flux.fromIterable() 返回作为一个串联字符串返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54856858/

相关文章:

java - JDBI 的@BindBean 在 INSERT 期间没有在 bean 类中找到命名参数

spring - 我可以使用 Spring Integration 作为守护进程来轮询目录吗?

java - Spring LDAP 错误代码 32 - 没有这样的对象];剩余名称 '/' "

java - 如何根据注释为 @Autowire 字段提供不同的 bean 实现?

java - 使用外部 Https 主机进行 Spring Boot 测试的 WireMock

java:检查 jar 版本之间的兼容性

java - 为一个模型创建多个 DTO 是一个好习惯吗?

java - 更改字体大小时遇到​​问题

spring - 使用 Spring Session Factory 时如何配置 Hibernate

java - 在进一步处理之前验证 JSON