Joy
Joy

Reputation: 4503

Emitting Server Sent Events about a resource update in Spring Boot application

I am new to Server-Sent events. I am working with a Spring Boot application with a front-end in React.

Here, we have a requirement, if, at the same time, more than one user opens a resource in UI, then the app needs to notify all these users in case, one of them is updating the same resource.

In this regard, I was searching for a relevant article in order to integrate Server-Sent Event with my Spring Boot application, I found: https://betterprogramming.pub/server-sent-events-on-react-and-spring-webflux-5f532b04633.

From this, what I understood is that, I have to add web flux dependency to the existing Spring Boot application and expose an endpoint for emitting the event.

But in my app, an update of the resource is being done with end-point: /api/resource1 and events are going to be emitted from the app with another end-point: /api/end-point-2 as follows:

The main resource endpoint responsible for updating the object is as follows:

 @RestController
    public class ResourceController {
    
        @CrossOrigin(allowedHeaders = "*")
        @GetMapping(value = "/api/resource1/")
        public MyObj updateMyObj(MyObj myObj) {
           ...
           return myRepository.save(myObj);
        }
    }

Other end-point responsible for emitting the event is going to be as follows:

@RestController
public class ResourceController { //THIS IS GOING TO NOTIFY THE CLIENTS AT 1 SEC INTERVAL

    @CrossOrigin(allowedHeaders = "*")
    @GetMapping(value = "/api/end-point-2/", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<MyObj> getMyObj() {
    
        return Flux.interval(Duration.ofSeconds(1))
                .map(it ->  <NOT ABLE TO UNDERSTAND WHAT SHOULD I WRITE HERE>);

    }
}

Here, I am not able to understand, how an update in first end point will get communicated to the second end point in order to notify the clients.

Could anyone please help here ? Thanks.

Upvotes: 2

Views: 2169

Answers (1)

sk1lls
sk1lls

Reputation: 51

I am facing quite similar problem. It seems like FluxSink might be helpful to store emitted events.

Then you could use ApplicationEventPublisher to publish saved entity or just proper info: MyObjSavedEvent.

On the other hand this solution needs more changes in architecture structure and it seems like really well suitable for CQRS and event sourcing approach where we store events in event store.

I am still researching possible solutions. Gonna let you know if I come across something useful.

Upvotes: 0

Related Questions