【问题标题】:How to stream a fixed list using Spring webflux?如何使用 Spring webflux 流式传输固定列表?
【发布时间】: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


【解决方案1】:

我的错,我仍然配置了 CommonsRequestLoggingFilter(因为我之前有一个阻塞的普通 api)。过滤器以某种方式缓存了响应,因此响应只是完全发出。

没有过滤器,我的示例按照@Vusal 的说明工作。

【讨论】:

    猜你喜欢
    • 2018-01-13
    • 2021-11-12
    • 1970-01-01
    • 2022-01-21
    • 2023-01-31
    • 2019-07-01
    • 1970-01-01
    • 2018-06-05
    • 2021-03-13
    相关资源
    最近更新 更多