Vadym Ozarynskyi
Vadym Ozarynskyi

Reputation: 305

Flux responce instead of WebSocket (Spring boot)

I'm writing service that will send to users new data as it's come to my server. So server receives data and this all will go to users. I've used WebSocket for this purpose. Users subscribe for a topic and then receives information about new data. But I saw in WebFlux that we can return data continuously as in socket. For example

@GetMapping(value = "/test", produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
    public Flux<Object> testStreamOfData() {
        return Flux.generate(() -> "", (state, sink) -> "Hello from reactivness")
                .delayElements(Duration.of(2, ChronoUnit.SECONDS));
    }

Question is: can I implement same logic with Flux as with Socket?

For example, users will make a request to the server and will return responses when new data will come.

Upvotes: 1

Views: 1148

Answers (1)

Brian Clozel
Brian Clozel

Reputation: 59056

You can indeed use Flux to stream data with Spring WebFlux.

Spring WebFlux is using the "application/stream+json media type to stream line-delimited JSON and the "text/event-stream" for Server Sent Events. The former is quite useful for server to server communication (you need a client that supports this format), and the latter for server to browser communication (browsers natively support that).

So you can stream data to many clients and even share the same source (you should look into creating a single instance of Flux.share()).

Now I'm not sure if by "socket" you're referring to TCP sockets or socket.io. TCP sockets are pretty low-level, and WebFlux supports WebSockets if you're looking for similar features. If you're looking for higher level transports like STOMP/socket.io, which support subscriptions, then WebFlux doesn't support that yet (Spring Framework is currently working on RSocket support).

If you're looking into streaming data to browsers, then SSE is the best choice here (as JSON streaming is not natively supported).

Upvotes: 2

Related Questions