spring-webfluxreactorwebflux

not streaming response in Spring WebFlux Flux<DataBuffer>



    @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;
    }

When emiiter.next(dataBuffer) , I cannot get a response from webflux server.

when emitter.complete(), I get a total reponse. I want to get streaming in real time, how can I do it?


Solution

  • You probably need to learn more what is HTTP Streaming and how to enable it with 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

    There is special description of the Flux result:

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

    Emit server-sent events. The ServerSentEvent wrapper can be omitted when only data needs to be written (however, text/event-stream must be requested or declared in the mapping through the produces attribute).

    See my simple sample about streaming AMQP data into HTTP client: https://github.com/artembilan/sandbox/tree/master/amqp-to-webflux