Skip to content

Instantly share code, notes, and snippets.

@luvarqpp
Created October 13, 2022 13:08
Show Gist options
  • Save luvarqpp/dc941ab368504a525ac66716253b04d7 to your computer and use it in GitHub Desktop.
Save luvarqpp/dc941ab368504a525ac66716253b04d7 to your computer and use it in GitHub Desktop.
sample ReactiveController in spring, for stackoverflow question
@Controller
@Slf4j
public class ReactiveController {
record SomeDTO(String name, String address) {
}
private final Sinks.Many<SomeDTO> eventSink = Sinks.many().replay().latest();
@RequestMapping(path = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<SomeDTO>> sse() {
final AtomicLong counter = new AtomicLong(0);
return eventSink.asFlux()
.map(e -> ServerSentEvent.builder(e)
.id(counter.incrementAndGet() + "")
//.event(e.getClass().getName())
.build());
}
// note, when you want this to work in production, ensure, that http request is not being cached on its way, using POST method for example.
@ResponseStatus(HttpStatus.OK)
@ResponseBody
@GetMapping(path = "/sendSomething", produces = MediaType.TEXT_PLAIN_VALUE)
public String sendSomething() {
this.eventSink.emitNext(
new SomeDTO("name", "address"),
(signalType, emitResult) -> {
log.warn("Some event is being not send to all subscribers. It will vanish...");
// returning false, to not retry emitting given data again.
return false;
}
);
return "Have a look at /sse endpoint (using \"curl http://localhost/sse\" for example), to see events in realtime.";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment