0

    @GetMapping(value = "/download")
    public Flux<DataBuffer> flux(ServerHttpResponse response) throws IOException {
        final Stream<Integer> stream = Stream.iterate(1, i -> i + 1).limit(1000);

        String fileName = String.format("%s.csv", RandomStringUtils.randomAlphabetic(10));
        response.getHeaders().set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
        response.getHeaders().setContentType(MediaType.APPLICATION_OCTET_STREAM);

        final Flux<DataBuffer> next = Flux.<DataBuffer>create(emitter -> {
                    stream
                            .map(i -> String.format("%d", i).getBytes(StandardCharsets.UTF_8))
                            .forEach(bytes -> {
                                final DefaultDataBuffer dataBuffer = new DefaultDataBufferFactory().allocateBuffer();
                                final OutputStream outputStream = dataBuffer.asOutputStream();
                                try {
                                    outputStream.write(Byte.decode("DD"));
                                    outputStream.flush();
                                    emitter.next(dataBuffer);
                                } catch (IOException  e) {
                                    e.printStackTrace();
                                }
                            });
                    emitter.complete();
                }
        );

        return next;
    }

emiiter.next(dataBuffer),我无法从 webflux 服务器获得响应。

什么时候emitter.complete(),我得到一个总的回应。我想实时获得流媒体,我该怎么做?

4

1 回答 1

1

您可能需要了解更多什么是 HTTP 流以及如何使用 Spring WebFlux 启用它:

https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-async-http-streaming

https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-codecs-streaming

结果有特殊说明Flux

https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-ann-return-types

发出服务器发送的事件。当ServerSentEvent只需要写入数据时,可以省略包装器(但是,text/event-stream必须通过生产属性在映射中请求或声明)。

请参阅我关于将 AMQP 数据流式传输到 HTTP 客户端的简单示例:https ://github.com/artembilan/sandbox/tree/master/amqp-to-webflux

于 2021-12-17T17:08:18.213 回答