【发布时间】:2019-12-03 14:30:54
【问题描述】:
我想使用Flux 将定义数量的数据流式传输到客户端。让客户端一一接收数据,不用等到我的服务器准备好完整列表。
因此我创建了以下示例。我希望每个数字的打印延迟为 1 秒:
@RestController
public class WebfluxServlet {
private static final List<String> inventory = Arrays.asList("1", "2", "3", "4", "5");
@GetMapping("/flux1")
public Flux<String> flux1() {
return Flux.fromIterable(inventory).delayElements(Duration.ofSeconds(1));
}
@GetMapping("/flux2")
public Flux<String> flux2() {
Flux<Long> interval = Flux.interval(Duration.ofSeconds(1));
Flux<String> events = Flux.fromIterable(inventory);
return Flux.zip(events, interval, (key, value) -> key);
}
}
使用简单的curl localhost:8080/flux 测试端点:
-
/flux1立即输出12345,没有任何延迟。 -
/flux2等待 5 秒,然后立即输出12345。
两者都不像我预期的那样。
有趣的是,如果我添加@GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE),我将直接获取流事件。但我的目标是拥有stream+json。我怎样才能得到这个?
【问题讨论】:
-
您的示例在我的情况下效果很好。这是我唯一的依赖:
implementation 'org.springframework.boot:spring-boot-starter-webflux'
标签: java spring spring-mvc spring-webflux reactive