Search code examples
javaspringspring-bootweb

How to write a web api replies very slowly with an infinite stream of text using java?


I want to write a web api that returns same text every 5 seconds in an infinite stream using java. What are the possible ways? and how to do it?

example:

curl 'https://localhost:8080/abcd'

response as below :

"some text"
.
.<wait 5 seconds>
.
"some text"
.
.<wait 5 seconds>
.
"some text"
.
.
etc...

Solution

  • Using Spring Webflux

    Option #1

    @GetMapping("")   
    public Flux<ServerSentEvent<String>> getStreamEvents() {
                return Flux.interval(Duration.ofSeconds(5))
                        .map(sequence -> ServerSentEvent.<String>builder()
                                .id(String.valueOf(sequence))
                                .event("periodic-event")
                                .data("something...")
                                .build());
         }
    

    Option #2

    @GetMapping(path = "/", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamFlux() {
        return Flux.interval(Duration.ofSeconds(1))
          .map(sequence -> "Flux - " + LocalTime.now().toString());
    }