我有一个 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/