bizzysven
bizzysven

Reputation: 21

Spring Webflex: Push Server Sent Event to Specific Users

I have been following this for reference. I am developing a spring-boot app which will have authenticated users. Once logged in, a user will subscribe to an event by visiting a specific URL.

This spring-boot app will also either support MQTT (or maybe just HTTP requests) in which information for a specific user will be sent. I would like to then display this sent information to the user using web flux/SSE if the user has subscribed.

Many users can be logged in at any given time, and they will have all subscribed to the updates. How do I manage all the different sinks for each logged in user?

I believe it's possible to get the current user when they visit the authenticated URL, but what's a method of storing all of the sinks for each logged in user?

I appreciate it.

Upvotes: 2

Views: 2685

Answers (1)

vins
vins

Reputation: 15370

You already got the answer in the comment section.

Lets assume that this is the message format you would be publishing.

public class Message {

    private int intendedUserId;
    private String message;

    // getters and setters

}

Just have 1 processor and sink from the processor.

 FluxProcessor<Message> processor;
 FluxSink<Message> sink;

Push all the messages via the sink.

sink.next(msg);

Your controller would be more or less like this. Here I assume you have some method to get the user id authtoken.getUserId(). Here the filter is part of the Flux.

@GetMapping(value = "/msg", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<Message> getMessages(){
    return processer
                .filter(msg -> msg.getIntendedUserId() == authtoken.getUserId());
}

Upvotes: 3

Related Questions