Closed tcltien closed 7 years ago
Hi
You could do it with multiple events. Every user subscribes to a different event. Then the application can send messages to each user individually
@GetMapping("/register/{clientId}/{event}")
public SseEmitter register(@PathVariable("clientId") String clientId,
@PathVariable("event") String event) {
return this.eventBus.createSseEmitter(id, event);
}
User subscribes to one event
eventSource = new EventSource(`/register/${uuid}/eventA`);
Other user subscribes to another event
eventSource = new EventSource(`/register/${uuid}/eventB`);
On the server you can then send events to each user individually
this.eventPublisher.publishEvent(SseEvent.of("eventA", data));
this.eventPublisher.publishEvent(SseEvent.of("eventB", data));
I complety forgot that SseEvent is able to address clients. This way everybody can subscribe to the same topic.
With addClientId the application can send an event to specific clients.
SseEvent event = SseEvent.builder().event("event").data("data").addClientId("123").build();
this.eventPublisher.publishEvent(event);
With addExcludeClientId the application can send events to all except the listed users.
event = SseEvent.builder().event("event").data("data").addExcludeClientId("123").build();
this.eventPublisher.publishEvent(event);
Hi ralscha,
Thank you. I'll try your way to implement.
But i have some question like this Ex: I have 2 user with id = [1,2] after subscribe 1 event like "unit" how can i check who is subscribe this event when publish
event = SseEvent.builder().event("event").data("data").addExcludeClientId(???).build();
Hi Sorry I missed your question. That's currently not supported by the library, you have to track the users in your code.
But internally the SseEventBus class holds a collection of all registered users, there are just no methods to query this collection.
I will look into it this week and maybe add a few methods to the class. Then you could simply ask the SseEventBus if a user is registered. Something like this
this.sseEventBus.isUserSubscribed(String clientId, String event)
I keep you posted
I added the following methods to the SseEventBus class. I will release a new version of the library today.
Set<String> getAllClientIds()
Set<String> getAllEvents()
Map<String, Set<String>> getAllSubscriptions()
Set<String> getSubscribers(String event)
int countSubscribers(String event)
boolean hasSubscribers(String event)
Thank for your effort @ralscha ,
At now i don't know what is your enhance so I'll share a litte experience i learned, we can using a RxJava for this case. We can create a observable object for handle each subscribe for each user and RxJava will handle when user unsubscirbe. Hope it useful
Hi ,
Can i ask a question? i have multiple user login to page, eventbus can send right data for each user logged